我如何解析多个节点&在一个XML文件中的子节点? 这里的文件结构:在全局节点内解析多个xml节点和子节点?
<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>
我尽量让读者解析器对于这一点,和他sucessufy读取对象和属性键, 但我没有想法,我怎么能读节点及其子节点这种格式(如XML的例子) 我的读者是:
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;
}
}
}
}
请在C#在这种情况下,XML解析节点和子节点的任何解决方案?我认为nodeList=root.SelectNodes()
- 在这个原因中不是更好的主意。 <subobjects>
- 是对象的子节点,并且它具有它们的非静态(对于每个对象 - 不同)类型的子对象。任何想法?
您没有使用[XDocument](http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx)而不是XmlDocument的任何原因(在我给出完整答案之前使用XDocument)? –
XmlDocument没有特定的原因。但是我很乐意看到,如何在XDocument上做到这一点!学习 - 永远不会太晚。 –
你知道你可以使用XPath来选择节点......对吧? XmlNodeList MyNodes = XDoc.SelectNodes(“// subobject2 | // subobject3”); –