dps123
dps123

Reputation: 1073

LINQ to XML XElement Node

I am creating a XML file using LinqXML.

string value = "Steet,<BR> </BR> City";
XElement address = new XElement("Address", value);

Once I write the xml file, the address value is shown as Steet,&lt;BR&gt &lt;/BR&gt I just need as it is like original. (Even if it does not well form)

Upvotes: 1

Views: 1751

Answers (3)

Joel Mueller
Joel Mueller

Reputation: 28764

I don't think you need to change anything. &lt; and &gt; are how angle brackets are escaped in XML. XML parsers turn them back into literal angle brackets automatically when reading string values. CDATA is simply another way of escaping the angle brackets. They both accomplish exactly the same thing in this case. If you take your original code and read the value of the <Address> node with an XML parser, the string returned will be Street,<BR> </BR> City. Changing the method of escaping to CDATA doesn't actually change anything except to make your XML (arguably) harder to read.

If you want the <BR /> tag to be actually part of the XML document, then you should make it part of the document. That is to say...

new XElement("Address", "Street,", new XElement("BR"), " City")

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167696

Well if that stuff is not well-formed then don't expect to be able to treat it as XML. Thus if you want to put not well-formed HTML markup into an XML element then consider to use a CDATA section e.g.

    string value = "Steet,<BR> </BR> City";
    XElement address = new XElement("Address", new XCData(value));

which will result in

<Address><![CDATA[Steet,<BR> </BR> City]]></Address>

If you want to parse the value as XML then do so with an XmlReader in fragment mode e.g.

static void Main()
{
    string value = "Steet,<BR> </BR> City";
    XElement address = new XElement("Address", ParseFragment(value));
    Console.WriteLine(address);
}

static IEnumerable<XNode> ParseFragment(string fragment)
{
    using (StringReader sr = new StringReader(fragment))
    {
        using (XmlReader xr = XmlReader.Create(sr, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment }))
        {
            xr.Read();
            XNode node;
            while (!xr.EOF && (node = XNode.ReadFrom(xr)) != null)
            {
                yield return node;
            }
        }
    }
}

That results in

<Address>Steet,<BR> </BR> City</Address>

Upvotes: 4

Kris Ivanov
Kris Ivanov

Reputation: 10598

you need to wrap it in CDATA to preserve it

Upvotes: 0

Related Questions