I am creating a XML file using LinqXML.
string value = "Steet,<BR> </BR> City"开发者_StackOverflow中文版;
XElement address = new XElement("Address", value);
Once I write the xml file, the address value is shown as Steet,<BR> </BR>
I just need as it is like original. (Even if it does not well form)
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>
I don't think you need to change anything. <
and >
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")
you need to wrap it in CDATA to preserve it
精彩评论