Vylic Vylic - 5 months ago 8
Java Question

Fill data in XML from another XML file dynamically (Java)

I have a xml file where I would like to fill in values from another xml file. For example, if I have

data.xml
:

<Data>
<Person>
<Name>neby</Name>
<Phone>
<Home>5553456789</Home>
<Mobile>5559879876</Mobile>
</Phone>
</Person>
</Data>


I want to fill in
test.xml
like this (Data taken from the above file):

<Test>
<Name>${Name}</Name>
<Number>${Home}</Number>
</Test>


In my Java program, I create XML files during runtime. I would like to give a file name, "pass" it to
test.xml
, have
test.xml
read it, and fill in the text.

Is there a way to do this?




Am I doing it correctly? All I get is the encoding. Never mind, I got it to work. Using the
data.xml
from above.

MyXSL.xsl:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" indent="yes"/>

<xsl:template match="/">
<xsl:for-each select="Data/Person">
<Test>
<Name><xsl:value-of select="Name"/></Name>
<Number><xsl:value-of select="Home"/></Number>
</Test>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>


Code:

try {
File stylesheet = new File("MyXSL.xsl");
File dataFile = new File("data.xml");

Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(dataFile);

StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(stringWriter));

System.out.println(stringWriter.toString());

} catch(Exception e){
e.printStackTrace();
}


Output:
<?xml version="1.0" encoding="UTF-8"?>


What am I doing wrong?
Above code works.

Answer

Create XSLT and then something like that (very simple from oracle java tuts):

// ...
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamSource; 
import javax.xml.transform.stream.StreamResult; 
// ... 

public class Stylizer {
    // ...
    public static void main (String argv[]) {
        // ...
        try {
            File stylesheet = new File(argv[0]);
            File datafile = new File(argv[1]);

            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.parse(datafile);
            // ...
            StreamSource stylesource = new StreamSource(stylesheet); 
            Transformer transformer = Factory.newTransformer(stylesource);
        }
    }
}

All informations and step-by-step guide to create XSLT and this sample app is here.

Comments