Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Escape characters in xml nodes

I have a xml like this in string variable ( load from file )

<Data>
    <Name>Test & <  test> </Name>
</Data>

when i try to load this xml i got exception "an error occured while parsing Node". i think this is due to & in Name tag. I have search on the internet but all solutions (e.g. SecurityElement.Escape) escape main xml elements too like greater than to gt and less than to lt and i only want to replace & in my case. i can iterate through xml and replace only data part but is there any shortest way ?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

AngleSharp has an error correcting "XML" parser that works more like an HTML5 or tag soup parser trying to correct and fix such markup errors. For your sample

using System;
using AngleSharp.Xml;
using AngleSharp.Xml.Parser;

namespace AngleSharpMalFormedXmlTest1
{
    class Program
    {
        static void Main(string[] args)
        {
            var malFormedXml =  @"<Data>
    <Name>Test & <  test> </Name>
</Data>";

            var doc = new XmlParser(new XmlParserOptions() { IsSuppressingErrors = true }).ParseDocument(malFormedXml);

            Console.WriteLine(doc.ToMarkup());
        }
    }
}

I get

<Data>
    <Name>Test &amp;&lt;  test&gt; </Name>
</Data>

But once you open up your input to such kind of mal-formed XML you can easily run into misconceptions and incompatibilities or tool-dependency which using a W3C standard like XML was meant to avoid.

over 4 years ago · Santiago Trujillo Report

0

Since you have no control over the source, you could try some regex to make it a valid xml:

string xml = @"<Data>
    <Name>Test & test&amp; &1 &lt;aaa &</Name>
</Data>";

xml = Regex.Replace(xml,@"&(?!\w+;)","&amp;");

this will return

<Data>
    <Name>Test &amp; test&amp; &amp;1 &lt;aaa &amp;</Name>
</Data>
over 4 years ago · Santiago Trujillo Report

0

The presented XML is not well-formed.

You can use CData section to make your XML well-formed.

  • Each <Name> should become <Name><![CDATA[
  • Each </Name> should become ]]></Name>

well-formed XML

<Data>
    <Name><![CDATA[Test & <  test> ]]></Name>
</Data>
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!