【问题标题】:XML parsing in JAVA, transformation from one Schema to otherJAVA中的XML解析,从一种Schema到另一种Schema的转换
【发布时间】:2012-03-28 10:00:39
【问题描述】:

如何在 java 中解析 XML。 我在下面给出了一个 XML:

<?xml version="1.0" ?>
<metabase>
  <response status="SUCCESS"/>
  <item>
    <id>10147417040</id>
    <description>
      <title>What part of the constitiution states the goals?</title>
      <language>English</language>
   </description>
   <pubDate>2012-03-27 07:25:33.0</pubDate>
  </item>
  <item>
    <id>10147417018</id>
    <description>
      <title>What is the work envelope of a robot car?</title>
      <language>English</language>
    </description>
    <pubDate>2012-03-27 07:25:33.0</pubDate>
  </item>
</metabase>

我想解析这个 XML 并转换成表单:

<?xml version="1.0" ?>
<add>
  <doc>
    <field name="id">10147417040</field>
    <field name="title">What part of the constitiution states the goals?</field>
    <field name="language">English</field>
    <field name="pubDate">2012-03-27 07:25:33.0</field>
  </doc>
  <doc>
    <field name="id">10147417018</field>
    <field name="title">What is the work envelope of a robot car?</field>
    <field name="language">English</field>
    <field name="pubDate">2012-03-27 07:25:33.0</field>
  </doc>
</add>

请提供一些示例 JAVA 代码来完成此任务。

谢谢 沙里克

【问题讨论】:

    标签: xml xsd xml-parsing xslt


    【解决方案1】:

    进行这种 XML 到 XML 转换的最佳方法是使用 XSLT。这是满足您需要的 XSLT:

    <xsl:stylesheet 
      version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:template match="text()">
      </xsl:template>
    
      <xsl:template match="item">
        <doc>
          <field name="id">
            <xsl:value-of select="id" />
          </field>
          <field name="title">
            <xsl:value-of select="description/title" />
          </field>
          <field name="language">
            <xsl:value-of select="description/language" />
          </field>
          <field name="pubDate">
            <xsl:value-of select="pubDate" />
          </field>
        </doc>
      </xsl:template>
    
      <xsl:template match="/">
        <add>
          <xsl:apply-templates/>
        </add>
      </xsl:template>
    
    </xsl:stylesheet>
    

    我不熟悉 Java,但我确信这是一种加载 XSLT 并将其应用于 XML 的简单方法 - 参见例如 http://www.devx.com/getHelpOn/10MinuteSolution/16635/1954

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      相关资源
      最近更新 更多