In C#, how to get XML node value that is white spa

2020-04-03 01:58发布

I have a XML node with a value which is a white space. Example:

<sampleNode> </sampleNode>

I am using a Serializer to get the data from XML document to store it in an object. Now, the problem I am facing is: If the XML node value contains nothing but a white space, as does the sample node above, the serializer interpretates it as a string.Empty.

How can I overcome this? I need get the actual white space, i.e. " ". Thanks a bunch!

标签: c# xml xmlnode
3条回答
戒情不戒烟
2楼-- · 2020-04-03 02:22

Assuming you are using XmlDocument, you should set the PreserveWhiteSpace property to True.

If using and XmlReader set the WhitespaceHandling property WhitespaceHandling.All.

See this MSDN article about Preserving White Space While Serializing.

The different serializers handle this different ways, try using the XmlTextReader for this, as per this forum post.

查看更多
放荡不羁爱自由
3楼-- · 2020-04-03 02:28

You can use a CDATA placeholder in order to avoid the removal of the space:

<sampleNode><![CDATA[ ]]></sampleNode>
查看更多
Bombasti
4楼-- · 2020-04-03 02:29

Sample class:

using System;

namespace GeneralTesting
{
    [Serializable]
    public class SampleNode
    {
        public string sampleNode = " ";
    }
}

And sample program:

    XmlSerializer xmls = new XmlSerializer(typeof(SampleNode));
    SampleNode sn = new SampleNode();
    using (FileStream fs = File.Open(@"C:\test.xml", FileMode.Create))
    {
        xmls.Serialize(fs, sn);
    }
    using (FileStream fs = File.OpenRead(@"C:\test.xml"))
    {
        XmlReaderSettings xmlrs = new XmlReaderSettings();
        xmlrs.IgnoreWhitespace = false;
        using (XmlReader xmlr = XmlReader.Create(fs, xmlrs))
        {
            Console.WriteLine("!{0}!", ((SampleNode) xmls.Deserialize(xmlr)).sampleNode); //output: ! !
        }
    }
查看更多
登录 后发表回答