无法使用XPath读取xml

时间:2011-11-10 08:50:45

标签: c# .net xml xpath xml-parsing

我需要在XMind包中解析content.xml文件 文件看起来像这样

<xmap-content xmlns="urn:xmind:xmap:xmlns:content:2.0" xmlns:fo="http://www.w3.org/1999/XSL   /Format" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink" version="2.0">

   <sheet id="sdfasdfsdf">
      <title> Sheet1 </title>
   </sheet>

   <sheet id="fgasdfgasr">
       <title> Sheet2 </title>
   </sheet>
<xmap-content>

我需要获取所有表格的标题列表。

我正在使用XPathExpression expr = navigator.Compile("//sheet");
但我猜它不起作用 该怎么办。任何建议或代码都可以 thnx提前。

2 个答案:

答案 0 :(得分:2)

您的XML已定义默认命名空间:urn:xmind:xmap:xmlns:content:2.0。因此,您需要使用前缀将其传递给XML引擎,然后使用表达式:

//ns:sheet

或其他方式:

//*[local-name() = 'sheet']

答案 1 :(得分:0)

XPathExpression expr =  navigator.Compile("xmap-content/sheet");

编辑:

string st = @"<xmap-content xmlns=""urn:xmind:xmap:xmlns:content:2.0"" xmlns:fo=""http://www.w3.org/1999/XSL   /Format"" xmlns:svg=""http://www.w3.org/2000/svg"" xmlns:xhtml=""http://www.w3.org/1999/xhtml"" xmlns:xlink=""http://www.w3.org/1999/xlink"" version=""2.0"">

            <sheet id=""sdfasdfsdf"">
                <title> Sheet1 </title>
            </sheet>

            <sheet id=""fgasdfgasr"">
                <title> Sheet2 </title>
            </sheet>
        </xmap-content>";

XmlDocument document = new XmlDocument();
document.LoadXml(st);

XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable); 

manager.AddNamespace("xm", "urn:xmind:xmap:xmlns:content:2.0"); 

var titles = document.SelectNodes("//xm:sheet/xm:title", manager);