Vylic Vylic -5 years ago 107
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



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


In my Java program, I create XML files during runtime. I would like to give a file name, "pass" it to
, have
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
from above.


<?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">
<Name><xsl:value-of select="Name"/></Name>
<Number><xsl:value-of select="Home"/></Number>



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

Document document = DocumentBuilderFactory.newInstance()

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


} catch(Exception e){

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

What am I doing wrong?
Above code works.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download