简体   繁体   English

以相同的名称读取不同级别的XML节点

[英]Read XML Node at different level with same name

i have an xml, which is have same element name at different level, i try to read it by using this code, 我有一个xml,在不同级别上具有相同的元素名称,我尝试使用此代码来读取它,

 xDoc.Load(url);
     XmlNodeList nodeList = xDoc.SelectNodes(string.Format("/DirectionsResponse/route"));
    foreach (XmlNode node in nodeList)
    {
        XmlElement companyElement = (XmlElement)node;

        kl = companyElement.GetElementsByTagName("summary")[0].InnerText;
        kl = companyElement.GetElementsByTagName("distance")[0].InnerText;
    }

i can read the summary element, but the problem is with the <distance> element, it read the first <distance> node that it found. 我可以读取summary元素,但是问题出在<distance>元素上,它读取了找到的第一个<distance>节点。 I want to read the <distance> element that not in <step> node. 我想读取不在<step>节点中的<distance>元素。

Can anyone show me how to do it 谁能告诉我该怎么做

在此处输入图片说明

From MSDN, on GetElementsByTagName : 从MSDN,在GetElementsByTagName

Returns an XmlNodeList containing a list of all descendant elements that match the specified Name. 返回一个XmlNodeList,其中包含与指定的Name匹配的所有后代元素的列表。

It's a complete sub-tree search , not a "select subnodes" function. 这是一个完整的子树搜索 ,而不是“选择子节点”功能。 For selecting a single subnode, use SelectSingleNode . 要选择单个子节点,请使用SelectSingleNode For a group like your "step" ones, use SelectNodes and iterate over them properly. 对于像“步骤”这样的组,请使用SelectNodes并对其进行正确的迭代。

You can use SelectSingleNode or SelectNodes in order to describe elements in XPath just like you have done this at line XmlNodeList nodeList = xDoc.SelectNodes("/DirectionsResponse/route"); 您可以使用SelectSingleNodeSelectNodes来描述XPath中的元素,就像您在XmlNodeList nodeList = xDoc.SelectNodes("/DirectionsResponse/route");行上做到的一样: XmlNodeList nodeList = xDoc.SelectNodes("/DirectionsResponse/route"); .

xDoc.Load(url);
XmlNodeList nodeList = xDoc.SelectNodes(string.Format("/DirectionsResponse/route"));
foreach (XmlNode node in nodeList)
{
    XmlElement companyElement = (XmlElement)node;

    kl = companyElement.SelectSingleNode("summary").InnerText; // summary node within current context
    kl = companyElement.SelectSingleNode("distance").InnerText;
}

should do the trick. 应该可以。

In my opinion, it is better to use all-purpose XPath SelectSingleNode and SelectNodes methods everywhere. 我认为,最好在各处使用通用的XPath SelectSingleNodeSelectNodes方法。
If you have any questions, read more about XPath at MSDN . 如果您有任何疑问, 请在MSDN上阅读有关XPath的更多信息

By the way , you can specify XmlElement as enumerated type and not convert it explicitly: 顺便说一句 ,您可以将XmlElement指定为枚举类型,而不必显式转换它:

xDoc.Load(url);
foreach (XmlElement element in xDoc.SelectNodes("/DirectionsResponse/route")) 
{
    kl = element.SelectSingleNode("summary").InnerText;
    kl = element.SelectSingleNode("distance").InnerText;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM