没有值的节点上的 XmlReader

XmlReader on node without value

我正在尝试从提供的 中提取数据并使用 XmlReader 将其添加到对象,但我注意到在没有值的节点上,我得到的是“\n”。

示例xml:

<Items>
 <Item>
  <NodeA>Some Value</NodeA>
  <NodeB>N</NodeB>
  <NodeC />
 </Item>
 <Item>
  ...
 </Item>
</Items>

我修改的部分C#:

while (sub_reader.ReadToFollowing("Item"))
{
    var item = new Item();

    sub_reader.ReadToFollowing("NodeA");
    sub_reader.Read();
    item.NodeA = sub_reader.Value;

    sub_reader.ReadToFollowing("NodeB");
    sub_reader.Read();
    item.NodeB = sub_reader.Value;

    sub_reader.ReadToFollowing("NodeC");
    sub_reader.Read();
    item.NodeC = sub_reader.Value;          //This return "\n    "

    this.Items.Add(item);
}

是否有任何 function/convenient 方法可以解决上述问题,但当 <NodeC /> 发生时 return 为 null 或空字符串?真正的 xml 要大得多,我不想对它们每个做 if else。

如有任何建议,我们将不胜感激。谢谢!

使用 XDocument <NodeC/> return string.Empty。这里dotNetFiddle

     string xml = @"<Items>
<Item>
  <NodeA>Some Value</NodeA>
  <NodeB>N</NodeB>
  <NodeC />
 </Item>
 <Item>
  <NodeA>Some 2223Value</NodeA>
  <NodeB>2223N</NodeB>
  <NodeC>12344</NodeC>
 </Item>
</Items>";

        XDocument doc = XDocument.Parse(xml);

        var result = doc.Root.Descendants("NodeC");

        foreach(var item in result)
        {
            Console.WriteLine(item.Value);
        }

如果你想将 XDocument 反序列化为某个对象,你可以检查这个答案:How do I deserialize XML into an object using a constructor that takes an XDocument?

public static MyClass FromXml (XDocument xd)
{
   XmlSerializer s = new XmlSerializer(typeof(MyClass));
   return (MyClass)s.Deserialize(xd.CreateReader());
}

与其调用 Read 然后调用 Value 属性,不如使用 ReadElementContentAsString 方法:

sub_reader.ReadToFollowing("NodeA");
item.NodeA = sub_reader.ReadElementContentAsString();

sub_reader.ReadToFollowing("NodeB");
item.NodeB = sub_reader.ReadElementContentAsString();

sub_reader.ReadToFollowing("NodeC");
item.NodeC = sub_reader.ReadElementContentAsString();