使用xslt将xml与自定义节点分开

时间:2013-08-22 09:18:04

标签: xslt-2.0

以下是我的xml摘录:

<?xml version="1.0"?>
    <catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>Superb story of army veteran</description>
   </book>
   </catalog>

我想在书的基础上拆分它,以便我得到它作为输出::

<Object-bean>
<child-bean>
 <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
</child-bean>

<child-bean>
<book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>Superb story of army veteran</description>
   </book>
</child-bean>
</Object-bean>

子bean节点我需要通过注释与java类映射,以便将子bean节点列表作为字符串。这是我的java代码::

 @XmlRootElement(name = "Child-bean")
 @XmlAccessorType(XmlAccessType.NONE)
    public class ChildBean {
@XmlAttribute(name="price")
private String price;
@XmlAttribute(name="country")
private String country;


public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

}

这是我的对象bean类::

@XmlRootElement(name = "Object-bean")
@XmlAccessorType(XmlAccessType.FIELD)
 public class ObjectBean {

@XmlAttribute(name = "name")
private String name;
@XmlAttribute
private String id;

@XmlElement(name="Child-bean")
private List<ChildBean> childList = new ArrayList<ChildBean>();
   }

1 个答案:

答案 0 :(得分:0)

我不了解您的XML与Java代码之间的关系,但就XSLT而言,您看起来好像只想将每个book元素包装到child-bean元素中想要转换根元素(catalog - &gt; Object-bean)所以你需要的只是

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

<xsl:template match="book">
  <child-bean>
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </child-bean>
</xsl:template>

<xsl:template match="/catalog">
  <Object-bean>
   <xsl:apply-templates select="@* | node()"/>
  </Object-bean>
</xsl:template>