tags:

views:

235

answers:

4
+2  Q: 

Java XML parsing.

Whats the quickest way to convert a doc like:

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

So that the elements with @ become attributes for the parent element.

ie get to:

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

Using a dom? or Sax parser or manually? and i can move the @ into the <>'s

+1  A: 

The best way to work directly with XML data is to use XQuery. It is not the easiest thing to learn, but if you work a lot with XML it is very useful.

Some IDE even support XQuery editing (like Oxygen XML).

http://de.wikipedia.org/wiki/XQuery http://www.oxygenxml.com/

lewap
A: 

Below link might be helpful

http://www.totheriver.com/learn/xml/xmltutorial.html#5

Mutant
+1  A: 

I think XSLT is the way to go.

More details here

And use a SAX parser, unless you have very good reasons.

chburd
+1  A: 

If you decide to use XSLT, it will look something like

  <!-- 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>
jelovirt