【问题标题】:Xpath - Find specific element, print all elements of that nodeXpath - 查找特定元素,打印该节点的所有元素
【发布时间】:2021-07-16 14:13:27
【问题描述】:

给定以下 Xpath 到一个元素

/std:Batch/BatchSection/ContractPartner/Contractor/Contract/contractNumber

如何打印节点合约的所有子元素 其中 sequenceNumber= 12345?

我试过了

xmllint --xpath "string(/std:Batch/BatchSection/ContractPartner/Contractor/Contract/contractNumber[contractNumber='12345'])" test.xml

但是,这是一个无效的 XPath 表达式。如何解决?

示例输入:

<std:Batch xmlns:std="http://www.test.com/contractBatch" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <year>2020</year>
  <batchType>3</batchType>
  <runDate>2020-04-11</runDate>
  <text>Datatest</text>
  <jobInfo>Test</jobInfo>
  <BatchSection>
    <addedAtDate>2020-04-11</addedAtDate>
    <ContractPartner>
      <contractDealerAG>44444</contractDealerAG>
      <contractorType/>
      <isoCountry>NL</isoCountry>
      <language>EN</language>
      <Contractor>
        <contractor>44444</contractor>
        <Contract>
          <contractor>44444</contractor>
          <sequenceNumber>12345</sequenceNumber>
          <info1>abcd</info1>
        </Contract>
      </Contractor>
    </ContractPartner>
  </BatchSection>
</std:Batch>

所需的输出(其中 sequenceNumber=12345):

    <Contract>
      <contractor>44444</contractor>
      <sequenceNumber>12345</sequenceNumber>
      <info1>abcd</info1>
   </Contract>

【问题讨论】:

  • 相应地编辑了我的帖子
  • 现在有效。

标签: xpath xml-namespaces xmllint


【解决方案1】:

不幸的是,您必须处理可怕的命名空间...试试这样:

xmllint --xpath "//*[local-name()='Contract'] [.//*[local-name()='sequenceNumber'][./text()='12345']]" test.xml

看看它是否有效。

【讨论】:

  • 这正是我所需要的,完美运行。谢谢! - 处理命名空间是指必须将前缀 local-name() 放在每个元素的前面?
  • @royskatt 不幸的是,命名空间远不止这些。您必须查找它(此处,例如:courses.ischool.berkeley.edu/i290-8/s04/lectures/2/…)。
【解决方案2】:

我假设您的意思是 sequenceNumber,根据 xml 示例,如果是这种情况,那么您可能需要执行类似的操作来返回节点合同:

xmllint --xpath "//sequenceNumber[.="12345"]/.." test.xml

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 2020-08-20
    • 2021-06-14
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2014-03-21
    相关资源
    最近更新 更多