Search code examples
c#xmlxmlreader

XmlReader on node without value


I'm trying to extract data from provided and add that to object using XmlReader, but I noticed on nodes without value, I get "\n " instead.

Example xml:

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

Part of my modified 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);
}

Is there any function/convenient way that work the above but return null or empty string when <NodeC /> happens? The real xml is much larger and I don't want to do if else on each of them.

Any suggestion is appreciated. Thanks!


Solution

  • Rather than calling Read followed by taking Value property, use ReadElementContentAsString method:

    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();