【问题标题】:XmlReader on node without value节点上的 XmlReader 没有值
【发布时间】:2016-11-28 20:55:21
【问题描述】:

我正在尝试从提供的 中提取数据并使用 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);
}

&lt;NodeC /&gt; 发生时,是否有任何功能/方便的方式可以在上面工作但返回 null 或空字符串?真正的 xml 要大得多,我不想对它们每个都做 if else。

感谢任何建议。谢谢!

【问题讨论】:

  • 似乎您已经有与您的 xml 结构相对应的类。所以使用XmlSerializer从xml获取数据。
  • @Fabio XmlSerializer 效果很好,因为它是我得到的更简单的 XML 之一,所以为这个对象使用了这个。谢谢!

标签: xml c# xml xmlreader


【解决方案1】:

而不是调用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();

【讨论】:

  • 我实际上在上面使用@Fabio 评论使用XmlSerializer 解决这个问题,因为这是更简单的xml 之一。但这绝对是我问题的答案。谢谢!
【解决方案2】:

使用 XDocument &lt;NodeC/&gt; 返回 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());
}

【讨论】:

  • 有趣,让我来玩玩。我以前从未使用过 XDocument。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多