I'm trying to extract data from provided xml 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!
Using XDocument <NodeC/>
return string.Empty
. Here 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);
}
If you want to deserialize the XDocument
to some object you can check this answer: 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());
}
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.