Java XML 解析

标签 java xml dom sax

转换文档的最快方法是什么:

<customermodel:Customer>
    <creditCards>
        <cardNumber>@0</cardNumber>
        <provider>@HSBC</provider>
        <xsi:type>@customermodel:CreditCard</xsi:type>
             23242552
    </creditCards>
    .
    .

这样带有@的元素就成为父元素的属性。

即到达:

<customermodel:Customer>
    <creditCards cardNumber="0" provider="HSBC" xsi-type="customermodel:CreditCard>
         232323232
    </creditCards>
        .
        .

使用 dom?或 Sax 解析器或手动?我可以将 @ 移至 <> 的

最佳答案

如果您决定使用 XSLT,它将看起来像这样

  <!-- process element and attributes first so that whitespace doesn't interfere -->
  <xsl:template match="creditCards">
    <xsl:copy>
      <xsl:apply-templates select="* | @*"/>
      <xsl:apply-templates select="text()"/>
    </xsl:copy>    
  </xsl:template>

  <!-- change childrent of creditCards to attributes and strip first charcter from value -->
  <xsl:template match="creditCards/*">
    <xsl:attribute name="{name()}">
      <xsl:value-of select="substring(., 2)"/>
    </xsl:attribute>
  </xsl:template>

  <!-- rename xsi:type -->
  <xsl:template match="creditCards/xsi:type">
    <xsl:attribute name="xsi-type">
      <xsl:value-of select="substring(., 2)"/>
    </xsl:attribute>
  </xsl:template>

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

关于Java XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/714056/

相关文章:

java - 对我来说,进行这些空检查并提高此代码的性能的更好方法是什么

java - 如何在 AssertJ 中为集合创建自定义断言

java - 资源加载: How to determine if it's a directory

java - 在 SWT 树中选择单元格(多列)

xml - 将日期添加到 logback.xml

java - log4j 2 向控制台附加程序添加多种颜色

java - 使用 JAXB 解码 XML,其中 SOAP 信封是子元素

javascript - DOM 事件总是单线程运行吗?

javascript - 在 javascript 中跟踪创建的窗口的关闭

javascript - Angular 2.0 Beta - 访问 DOM 适配器 - BrowserDomAdapter