【问题标题】:Unable to read xml with XPath无法使用 XPath 读取 xml
【发布时间】:2011-12-25 23:44:09
【问题描述】:

我需要解析 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");
但我想它不起作用
该怎么办。任何建议或代码都可以。
提前谢谢。

【问题讨论】:

  • 如何获得&lt;title&gt; 值一旦我有给定XPathNavigator&lt;sheet&gt; ......好吧,我正在使用XPathNodeIterator iterator = navigator.Select("//xm:sheet", manager); 进行迭代

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


【解决方案1】:

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

//ns:sheet

或其他方式:

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

【讨论】:

  • 如何将默认命名空间传递给 xml 引擎。使用 XPath
  • @j4m4l,使用XmlNamespaceManagermsdn.microsoft.com/en-us/library/tywd160x.aspx
  • XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable); manager.AddNamespace("xm", "urn:xmind:xmap:xmlns:content:2.0"); XPathExpression expression = navigator.Compile("/xm:sheet"); XPathNodeIterator iterator = navigator.Select("/xm:sheet", manager); XPathNodeIterator iterator = navigator.Select("/xm:sheet", manager); 我正在使用以下代码但仍然无法正常工作?
  • @j4m4l,试试//xm:sheet 而不是/xm:sheet
  • thnx 很多...但我需要再问一件事,一旦我拥有给定XPathNavigator&lt;title&gt;&lt;sheet&gt; 后如何获得&lt;title&gt;
【解决方案2】:

试试

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);

【讨论】:

    猜你喜欢
    • 2016-03-14
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 2011-02-18
    相关资源
    最近更新 更多