XML-查找节点,用一个文本节点打印其祖先




问题听起来不清楚,所以我将使用示例。

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<root>
  <item>
    <item>
      <item>
        <item>
          <key>test1</key>
          <Name>Daugther E</Name>
        </item>
        <Name>Son C</Name>
      </item>
      <Name>Child B</Name>
    </item>
    <Name>Item A</Name>
  </item>
</root> 

我很容易找到带有XPath的Daugthere。我想要一些灵活的方式来打印整个层次结构,例如

[项目A] -> [CHILD B] -> [儿子C] -> [女儿E]

有可能吗?这将为我节省很多乏味的手动搜索和验证。我目前在Windows上使用XMLStarlet查询和编辑XML。我可以创建Python脚本来解析XML DOM树并打印结果,但是也许有更强大或更轻松的方法可以做到。

i解决了XSLT的问题:
是否可以在XSLT处理过程中导航到匹配节点的父节点? - 这篇文章是巨大的帮助

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" omit-xml-declaration="yes"/>
  <xsl:template match="//Name[text()='Daugther E']/">
    <xsl:if test="count(ancestor::item) &gt; 1">
      <xsl:apply-templates select="ancestor::item[1]/ancestor::item[1]" mode="backout"/><xsl:text> -></xsl:text>
    </xsl:if>
    <xsl:text>[</xsl:text><xsl:value-of select="."/><xsl:text>]</xsl:text>
  </xsl:template>
  <xsl:template match="item" mode="backout">
    <xsl:choose>
      <xsl:when test="count(ancestor::item) &gt; 0"><xsl:text> - </xsl:text>
        <xsl:apply-templates select="ancestor::item[1]" mode="backout"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:text>&#xa;</xsl:text>
      </xsl:otherwise>
    </xsl:choose>
    <xsl:if test="count(ancestor::item) &gt; 0">
      <xsl:text> -></xsl:text>
    </xsl:if>
    <xsl:text>[</xsl:text><xsl:value-of select="Name/."/><xsl:text>]</xsl:text>
  </xsl:template>
  <xsl:template match="text()"/>
</xsl:stylesheet>

最新更新