-1

suppose that we have this node in xml:

<person>
   <name>Name</name>
   <lastName>LastName</lastName>
</person>

I want to iterate, using Java, into that node and then for each element I want to show he's position in that node.

In that case, output should be: name: position 0, lastName: position 1

Thanks !

Nicolas
  • 83
  • 1
  • 7

2 Answers2

0

You should be able to get all the nodes in some kind of set or tree model. I'm used to Json but XML should be similar in that regards. You should iterate by getting the iterator object and call "withIndex()" then call forEach. Youll be given objects of type IndexedValue where T is the type you're iterating. Or you can use Kotlins built in extension function "forEachIndexed" which will give you two params: index, value.

Alex Couch
  • 151
  • 4
0

You can use XSLT from Java to get the desired output. For this, create the following files:

Name your input file 'input.xml':

<?xml version="1.0" encoding="UTF-8"?>
<person>
   <name>Name</name>
   <lastName>LastName</lastName>
</person>

Create a transform.xslt:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="UTF-8" indent="yes" omit-xml-declaration="yes" />

  <xsl:template match="/person">
    <xsl:for-each select="*">
        <xsl:value-of select="concat(name(),': position ',position()-1)" />
        <xsl:if test="position() != last()">, </xsl:if>        
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

And use the Java file from this SO answer:

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class TestMain {
    public static void main(String[] args) throws IOException, URISyntaxException, TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        Source xslt = new StreamSource(new File("transform.xslt"));
        Transformer transformer = factory.newTransformer(xslt);

        Source text = new StreamSource(new File("input.xml"));
        transformer.transform(text, new StreamResult(new File("output.text")));
    }
}

Then execute the Java code (i.e. like this):

javac TestMain.java
java  TestMain

Now the output.text file contains the desired text.

zx485
  • 28,498
  • 28
  • 50
  • 59