2

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
  • use vtd-xml, better than DOM, SAX or Pull. Commented Mar 20, 2011 at 3:10

4 Answers 4

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

1

I think XSLT is the way to go.

More details here

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

Comments

0

Below link might be helpful

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.