无法正确制定XPath语法以在复杂的xml文件中进行搜索

时间:2015-09-22 16:52:24

标签: xml xpath

我在正确制定我的XPath以研究XML文件时遇到问题我是使用4.0 net框架的Visual Basic 2015并且它在excel模板中

以下是xml文件的一部分

      <Data ss:Type="String">1000102043</Data>
    </Cell>
    <Cell>
      <Data ss:Type="String"></Data>
    </Cell>
    <Cell>
      <Data ss:Type="Number">1.0</Data>
    </Cell>
    <Cell>
      <Data ss:Type="String">Lot / Fourre-tout</Data>
    </Cell>
    <Cell ss:StyleID="Currency">
      <Data ss:Type="Number">320,38</Data>
    </Cell>
    <Cell ss:StyleID="Currency">
      <Data ss:Type="Number">320,38</Data>
    </Cell>
    <Cell>
      <Data ss:Type="String">CAD</Data>
    </Cell>
    <Cell>
      <Data ss:Type="Number">1.0</Data>

我只需要在搜索中找到“数字”字段的行,其中ss:Type =“Number”

此时我只能使用此

获取所有“数据”字段
xmlNodePrice = xmlDoc.GetElementsByTagName("Data")

所以这可行,但我只需要数字行

我试过这个

xmlNodePrice = xmlDoc.GetElementsByTagName("//Data(@Type='Number')")

还有这个

xmlNodePrice = xmlDoc.GetElementsByTagName("//Data[@Type='Number''")

仍然没有去

2 个答案:

答案 0 :(得分:0)

xmlNodePrice = xmlDoc.GetElementsByTagName("//Data[@Type='Number''")

这会调用GetElementsByTagName()并按照其名称建议:它采用标记名称并选择与标记名称匹配的元素。

如果你想使用XPath,你可以使用SelectNodes()SelectSingleNode(),它们需要一个完整的XPath,而不仅仅是一个标记名作为它们的第一个参数。重载(带有第二个参数)可以使用命名空间管理器。有关详细信息和示例,请参阅上面的link from LarsH和上面的两个链接。

答案 1 :(得分:0)

感谢您的回答,它引导我朝着正确的方向前进,但我还有很多工作要做,以便完成其余工作。

这是我的最终代码WORKING

    Public strPathFile As String
    Dim xmlDoc As New XmlDocument
    Dim xmlNode As XmlNodeList
    Dim nsMgr As XmlNamespaceManager
    Dim selectedNodes As XmlNodeList

    xmlDoc.Load(strPathFile)

    nsMgr = New XmlNamespaceManager(xmlDoc.NameTable)
    nsMgr.AddNamespace("o", "urn:schemas-microsoft-com:office:office")
    nsMgr.AddNamespace("x", "urn:schemas-microsoft-com:office:excel")
    nsMgr.AddNamespace("html", "http://www.w3.org/TR/REC-html40")
    nsMgr.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet")

    selectedNodes = xmlDoc.SelectNodes("/ss:Workbook/ss:Worksheet/ss:Table/ss:Row/ss:Cell/ss:Data[@ss:Type=""Number""]", nsMgr)
    For Each selectedNode As XmlNode In selectedNodes
        'Do whatever
        End If
    Next

这是xml文件

    </Cell>
    <Cell>
      <Data ss:Type="String">each / par pi&#232;ce</Data>
    </Cell>
    <Cell ss:StyleID="Currency">
      <Data ss:Type="Number">0,51</Data>
    </Cell>
    <Cell ss:StyleID="Currency">
      <Data ss:Type="Number">1,02</Data>
    </Cell>
    <Cell>
      <Data ss:Type="String">CAD</Data>
    </Cell>
    <Cell>
      <Data ss:Type="Number">0.0</Data>