简体   繁体   English

在Java中应用XSLT在XML输出中获取输入XML标签名称

[英]Get input XML tags name in XML output applying XSLT in java

I'm new to xslt. 我是xslt的新手。

What I want is get the tag names from input xml by applying xslt and save the output in output.xml 我想要的是通过应用xslt从输入xml中获取标签名称,并将输出保存在output.xml中

My input.xml is - 我的input.xml是-

<?xml version="1.0" encoding="UTF-8"?>
<productDetails>
<name>Mobile</name>
<price>999</price>
<stock>57</stock>
</productDetails>

My input.xsl is - 我的input.xsl是-

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

<xsl:template match="/productDetails">
   <xsl:attribute name="name()"/>   
</xsl:template>
</xsl:stylesheet>

My java code is - 我的Java代码是-

   Source xmlInput = new StreamSource("input.xml");
    Source xsl = new StreamSource(new File("input.xsl"));
    Result xmlOutput = new StreamResult(new File("output.xml"));


        Transformer transformer = TransformerFactory.newInstance().newTransformer(xsl);
        transformer.transform(xmlInput, xmlOutput);

Output what I want is - 输出我想要的是-

<?xml version="1.0" encoding="UTF-8"?>
 name
 price
 stock

Please anyone help 请任何人帮助

Thank you in advance. 先感谢您。

Write a template 写一个模板

<xsl:template match="*">
  <xsl:value-of select="name()"/>
</xsl:template>

if you want to output the name of all elements in the input. 如果要输出输入中所有元素的名称。 If you only need the name of the leaf elements then use 如果只需要叶子元素的名称,请使用

<xsl:template match="*[not(*)]">
  <xsl:value-of select="name()"/>
</xsl:template>

You might need or want to add white space for better formatting of the result. 您可能需要或想要添加空格以更好地格式化结果。 And not that you said you want an XML result yet the result sample you showed with the pure text nodes at the main level is not a well-formed XML document. 并不是说您想要一个XML结果,而是在主层上使用纯文本节点显示的结果样本不是格式正确的XML文档。 XSLT however allows the output of such fragments so if that format is what you want my suggestion should do. 但是,XSLT允许输出此类片段,因此,如果您希望这种格式是我的建议应该做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM