将SelectSingleNode与XML文件一起使用,节点重复两次

时间:2014-04-25 20:58:11

标签: asp.net xml xpath

这是我正在尝试解析的文件。我可以从<countryName><countryAbbrev>获取数据,但在尝试读取<gml:name>节点时收到错误。请注意,此节点在XML文件中,在顶层和<Hostip>节点下出现两次。 这是我正在使用的语法:

  • 这个有效 - doc.SelectSingleNode("//countryName")
  • 这个没有 - doc.SelectSingleNode("//gml:name")

有什么想法吗?

<HostipLookupResultSet xmlns:gml="http://www.opengis.net/gml" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0.1" 
 xsi:noNamespaceSchemaLocation="http://www.hostip.info/api/hostip-1.0.1.xsd">
    <gml:description>This is the Hostip Lookup Service</gml:description>
    <gml:name>hostip</gml:name>
    <gml:boundedBy>
        <gml:Null>inapplicable</gml:Null>
    </gml:boundedBy>
    <gml:featureMember>
        <Hostip>
            <ip>24.205.216.31</ip>
            <gml:name>Carson City, NV</gml:name>
            <countryName>UNITED STATES</countryName>
            <countryAbbrev>US</countryAbbrev>
            <ipLocation>
                <gml:pointProperty>
                    <gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
                        <gml:coordinates>-119.763,39.233</gml:coordinates>
                    </gml:Point>
                </gml:pointProperty>
            </ipLocation>
        </Hostip>
    </gml:featureMember>
</HostipLookupResultSet>

1 个答案:

答案 0 :(得分:1)

您需要为xmlns别名gml使用XmlNamespaceManager。试试这样:

XmlNamespaceManager nsmanager = new XmlNamespaceManager(doc.NameTable);
nsmanager.AddNamespace("gml", "http://www.opengis.net/gml");

Debug.WriteLine(doc.SelectSingleNode("//countryName").InnerText);
foreach (XmlNode node in doc.SelectNodes("//gml:name", nsmanager))
{
    Debug.WriteLine(node.InnerText);
}

结果:

UNITED STATES 
hostip 
Carson City, NV

修改

只是想一想,如果您尝试只访问其中一个gml:name节点,则以下xpath将分别导航第一个和第二个子树的子树:

//HostipLookupResultSet/gml:name/text()
//HostipLookupResultSet/gml:featureMember/gml:name/Hostip/text()