How i can parse multiple nodes & child nodes in one XML file? Here the file structure:
<objects>
<object id=1 name="test" param="1">
<attribute key = "test" value="1"/>
<subobjects>
<subobject id=2 value="test" param="some"/>
<subobject2 id=2 value="test" param="some"/>
<subobject3 id=2 value="test" param="some"/>
</subobjects>
</object>
<object id=2 name="newtest" param="44">
<attribute key = "test1" value="1"/>
<attribute key = "test2" value="2"/>
<attribute key = "test3" value="3"/>
<subobjects>
<subobject id=1 value="intvaluetest" param="1"/>
</subobjects>
</object>
</objects>
I am try to make a reader-parser for this, and him sucessufy reads object and attribute keys, but i dont have idea, how i can read node and their children nodes in this format (as on xml example) My reader is:
XmlDocument document = new XmlDocument();
document.Load(fileName);
foreach (XmlNode node in document.GetElementsByTagName("object"))
{
ushort id = ushort.Parse(node.Attributes["id"].InnerText);
//do some things
foreach (XmlAttribute attr in node.Attributes)
{
switch (attr.Name.ToLower())
{
case "name":
//do things
break;
case "param":
//do things
break;
}
}
if (node.HasChildNodes)
{
foreach (XmlNode attrNode in node.ChildNodes)
{
if (attrNode.Attributes != null &&
attrNode.Attributes.Count > 0 &&
attrNode.Attributes["key"] != null &&
attrNode.Attributes["value"] != null)
{
string value = attrNode.Attributes["value"].InnerText;
switch (attrNode.Attributes["key"].InnerText.ToLower())
{
case "test":
//do things with value
break;
}
}
}
}
Please, any solution in C# for XML parse nodes and child nodes in this case? I think nodeList=root.SelectNodes()
- non better idea in this cause. <subobjects>
- is children node of object, and this have a their non-static (for each object - different) type of sub-object. Any idea?
Would a recursive function work?
static void Main() {
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
ReadNode(doc.GetElementsByTagName("object")[0]);
Console.ReadLine();
}
static void ReadNode(XmlNode node) {
//Do something with each Node
if(node.Attributes.Count > 0) {
foreach(XmlAttribute attr in node.Attributes) {
//Do Something with each Attribute
}
}
if(node.HasChildNodes == true) {
foreach(XmlNode chlnode in node.ChildNodes) {
ReadNode(chlnode);
}
}
}
You could use XmlNode.Name
to know which node you're dealing with.
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.