简体   繁体   English

在使用XPATH查询之前,如何将正确的XML名称空间提供给管理器

[英]How to feed the correct XML namespaces to the manager before using XPATH queries

I've got the following graphml document on which I would like to perform XPATH queries 我有以下graphml文档,我想在该文档上执行XPATH查询

<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
     http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <graph id="G" edgedefault="undirected">
    <node id="n0"/>
    <node id="n1"/>
    <edge id="e1" source="n0" target="n1"/>
  </graph>
</graphml>

I would like to perform XPATH queries on this document but since it defines a namespace I'm not sure what the names of the nodes are. 我想在此文档上执行XPATH查询,但是由于它定义了名称空间,因此我不确定节点的名称是什么。 After searching here I found this question. 在这里搜索后,我发现了这个问题。 The accepted answer there is stripping of the namespace declaration and reloading the document so that you can use the local names (which defeats the point of XML namespaces), however there was also a comment which gave me the following syntax: 公认的答案是剥离名称空间声明并重新加载文档,以便您可以使用本地名称(这与XML名称空间的观点相违背),但是也有一条注释为我提供了以下语法:

var nodeList = input.SelectNodes("//*[local-name()='node']", nsmgr);

To be honest I don't really like this solution either. 老实说,我也不太喜欢这种解决方案。 To me it seems that using an XMLNameSpaceManager should solve this problem so I tried the following: 在我看来,使用XMLNameSpaceManager应该可以解决此问题,因此我尝试了以下操作:

string xmlns = input.DocumentElement.Attributes["xmlns"].Value;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(input.NameTable);
nsmgr.AddNamespace("graphml", xmlns); //Problematic?

var nodeList = input.SelectNodes("//node", nsmgr);

However using this //node doesn't give me any results, this is probably causes by the line which I marked problematic, I'm not sure how the namespace for GrapML is called and I cant find it in the XSD document (I don't know where to look). 但是使用此//node不会给我任何结果,这可能是由我标记为有问题的那一行引起的,我不确定如何调用GrapML的命名空间,并且无法在XSD文档中找到它(我不会不知道在哪里看)。 Anybody got any tips? 有人有提示吗?

The graphml namespace seems to be http://graphml.graphdrawing.org/xmlns (from http://graphml.graphdrawing.org/primer/graphml-primer.html ). graphml命名空间似乎是http://graphml.graphdrawing.org/xmlns (来自http://graphml.graphdrawing.org/primer/graphml-primer.html )。

So use nsmgr.AddNamespace("graphml", "http://graphml.graphdrawing.org/xmlns") to add it to the namespace manager and then select the nodes using something like: 因此,使用nsmgr.AddNamespace("graphml", "http://graphml.graphdrawing.org/xmlns")将其添加到名称空间管理器中,然后使用类似以下内容的节点进行选择:

var nodeList = input.SelectNodes("//graphml:node", nsmgr);

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

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