Reputation: 351
suppose I have the following XML string:
<?xml version="1.0" encoding="utf-8" ?>
<items>
<item1>value1</item1>
<item2>value2</item2>
<item3>value3</item3>
<item4>value4</item4>
<item5>value5</item5>
<item6>value6</item6>
</items>
I need to parse it in a generic way as it may be updated later, and I don't need to modify my code accordingly. So I have tried the following:
public static Dictionary<string, string> Parser(string xmlString)
{
Dictionary<string, string> parserDictionary = new Dictionary<string, string>();
using (StringReader stringReader = new StringReader(xmlString))
using (XmlTextReader reader = new XmlTextReader(stringReader))
{
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
parserDictionary.Add(reader.Name, reader.ReadString());
break;
}
}
}
return parserDictionary;
}
This code have 2 issues:
<items>
element with null value, I don't need to
parse it<item1>
please advise
Upvotes: 2
Views: 3482
Reputation: 31194
If you need to convert XML to an object representation than that's trivially easy
XDocument xDoc = XDocument.Parse(xmlString);
That's really all you need to do. Once you do that, you can query your xDoc
with the Elements
, Element
, Attribute
, Attributes
and Descendants
Properties.
For an example, here's some code that will print all of your values
XDocument xDoc = XDocument.Parse(xmlString);
foreach(XElement e in xDoc.Elements())
{
Console.WriteLine(e.Value);
}
Upvotes: 1
Reputation: 67898
Why not something like this:
var parserDictionary = XDocument.Create(xmlString)
.Descendants("items")
.Elements()
.Select(elem => new { Name = elem.Name.LocalName, Value = elem.Value })
.ToDictionary(k => k.Name, v => v.Value);
You could probably even do this:
var parserDictionary = XDocument.Create(xmlString)
.Descendants("items")
.Elements()
.ToDictionary(k => k.Name.LocalName, v => v.Value);
Upvotes: 7