如何用Java重写xml文件

用户名

我想重写XML文件的一小部分。

想法是,我可以处理以下情况:

<Line>
     <P Name="Src">5</P>
     <P Name="Dst">4</P>
</Line>

但是,有时,XML文件包含如下信息:

<Line>
    <P Name="Src">2</P>
    <P Name="Points">[3, 0]</P>
    <Branch>
      <P Name="Points">[0, 8]</P>
      <P Name="Dst">5</P>
    </Branch>
    <Branch>
      <P Name="Dst">3</P>
    </Branch>
</Line>

我想要的很简单,我想将上述正确信息重写为开始模式:

1)。删除<P Name="Points">[*,*]</P>

2)。放置<P Name="Src">*</P>到每个<Branch>

3)。更改<Branch><Line>

预期结果将是:

<Line>
     <P Name="Src">2</P>
     <P Name="Dst">5</P>
</Line>
<Line>
     <P Name="Src">2</P>
     <P Name="Dst">3</P>
</Line>

有什么建议或建议吗

谢谢

四十二

这是完成这项工作的XSLT。您可能需要调整何时包括或排除<P>元素的条件,这里它仅排除其文本节点<P>中具有[字符的元素

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <!-- By default, copy everything -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <!-- Special processing for Line elements that has one or more Branch children -->
    <xsl:template match="Line[count(Branch) > 0]">
        <xsl:apply-templates select="Branch" />
    </xsl:template>

    <!-- Special processing for Branch elements -->
    <xsl:template match="Branch">
        <Line>
            <xsl:apply-templates select="../P[not(contains(., '['))]" />
            <xsl:apply-templates select="P[not(contains(., '['))]" />
        </Line>
    </xsl:template>

</xsl:stylesheet>

还请注意,此XSL假定<Branch>元素不能作为<Line>元素的直接子元素出现在其他任何地方

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章