将xml节点子节点与xml标记一起使用

时间:2013-03-18 12:21:12

标签: xml xslt xpath

我有以下输入xml

<?xml version="1.0" encoding="UTF-8"?>  
<Parent>  
  <ParentElement1>PE1</ParentElement1>  
  <ParentElement2>PE2</ParentElement2>  
  <Child>  
    <ChildElement1>CE1</ChildElement1>  
    <ChildElement2>CE2</ChildElement2>  
  </Child>  
</Parent>

我需要在Parent中提取Child,

输出必须如下:

<Child>  
  <ChildElement1>CE1</ChildElement1>  
  <ChildElement2>CE2</ChildElement2>  
</Child>`

我尝试过使用XPath表达式/Parent/Child,  但它只选择文字CE1&amp; CE2。

1 个答案:

答案 0 :(得分:1)

此处的关键是使用<xsl:copy-of>代替<xsl:value-of>

来自XSL规范:The xsl:copy-of element can be used to copy a node-set over to the result tree without converting it to a string.

使用以下样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" />
<!-- To get rid of <?xml ... declaration, use the following:
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes" /> -->

<xsl:template match="/">
  <!-- use copy-of instead of value-of -->
  <xsl:copy-of select="/Parent/Child" />
</xsl:template>

</xsl:stylesheet>

输出:

<?xml version="1.0" encoding="UTF-8"?>
<Child>
   <ChildElement1>CE1</ChildElement1>
   <ChildElement2>CE2</ChildElement2>
</Child>