Xml with spaces as InnerText

2019-07-13 13:28发布

I'm parsing Xml data which has entries like this:

<item name="UserText" type_name="gh_string" type_code="10">      </item>

I'm supposed to read the 6 spaces as a String, but both the InnerText and InnerXml values of the System.Xml.XmlNode are zero length Strings.

Is there any way I can get at this whitespace data in existing files and what do I need to do in the future to prevent this sort of screw up?

3条回答
家丑人穷心不美
2楼-- · 2019-07-13 13:35

XML is ignoring that whitespace. If you need to preserve it, you should insert an xml:space="preserve" attribute into your elements. Something like this, which I think is going to preserve your whitespace wherever the XML is consumed.

<item xml:space="preserve" name="UserText" type_name="gh_string" type_code="10">      </item>

Another option that will work with LINQ-to-XML is to use the PreserveWhitespace load option. Example:

XElement element = XElement.Parse(xml, LoadOptions.PreserveWhitespace);

You should also be able wrap the whitespace in a CData tag, haven't tested.

查看更多
【Aperson】
3楼-- · 2019-07-13 13:45

If you use XMLDocument, set XMLDocument.PreserveWhitespace = true before calling Load.

See http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx

This works for me fine.

查看更多
放荡不羁爱自由
4楼-- · 2019-07-13 13:54

If you are reading in the xml with an XMLReader just use the XMLReaderSettings with IgnoreWhitespace set to false

XmlReader r = XmlReader.Create("file",new XmlReaderSettings{ IgnoreWhitespace=false;})
查看更多
登录 后发表回答