简体   繁体   中英

Transform XML file with Java

I want to convert one xml to another xml with the help of java code. I want to give one xml as input file and expecting another xml file as output. How we can do this thing with help of java? can anybody give suggestion to me.

Input.xml

<Order OrderNo=”1234567890”>

 <OrderLines>

  <OrderLine PrimeLineNo=”1” SubLineNo=”1”/>

  <OrderLine PrimeLineNo=”2” SubLineNo=”1”/>

 </OrderLines>

</Order>

output.xml file i need output this file like this

<Order OrderName="1234567890">

 <OrderLines MaxOrderNumbers=”2”>

  <OrderLine LineNumber="1" SubLineNumber="1"/>

  <OrderLine LineNumber ="2" SubLineNumber ="1"/>

 </OrderLines>

</Order>

But i have already tried the below code with help of java.

public class XmlToXml {

public static void main(String[] args) {

    final String xmlStr ="<Order OrderNo=\"1234567890\"><OrderLines><OrderLine PrimeLineNo=\"1\"                     SubLineNo=\"1\"/><OrderLine PrimeLineNo=\"2\" SubLineNo=\"1\"/></OrderLines></Order>";

    Document doc = convertStringToDocument(xmlStr);

    String str = convertDocumentToString(doc);

      System.out.println(str);
}

private static String convertDocumentToString(Document doc) {

    TransformerFactory tf = TransformerFactory.newInstance();

    Transformer transformer;
    try {
        transformer = tf.newTransformer();

         System.out.println(transformer.getParameter("xmlStr"));

        StringWriter writer = new StringWriter();

        writer.append("MaxOrderNumbers");

        transformer.transform(new DOMSource(doc), new StreamResult(writer));

        String output = writer.getBuffer().toString();

        return output;

    } catch (TransformerException e) {

        e.printStackTrace();
    }

    return null;
}

private static Document convertStringToDocument(String xmlStr) {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
    DocumentBuilder builder;  
    try 
    {  
        builder = factory.newDocumentBuilder(); 

        Document doc = builder.parse(new InputSource( new StringReader( xmlStr ) ) );

        return doc;

    } catch (Exception e) { 

        e.printStackTrace();  
    } 
    return null;
}
}

The way to tackle this is to define the transformation rules in XSLT.

You need one rule that copies things unchanged, by default:

<xsl:template match="*|@*">
 <xsl:copy>
  <xsl:apply-templates select="*|@*"/>
 </xsl:copy>
</xsl:template>

and then you need further rules to define the changes you want to make:

<xsl:template match="@OrderNo">
 <xsl:attribute name="OrderName"><xsl:value-of select="."/></xsl:attribute>
</xsl:template>

and similarly for the other renaming rules, plus

<xsl:template match="OrderLines">
 <OrderLines MaxOrderLines="{count(*)}">
  <xsl:apply-templates select="*|@*"/>
 </OrderLines>
</xsl:template>

Then, having assembled these rules into a stylesheet, you can run the transformation from your Java code, using code very similar to what you have already done:

TransformerFactory tf = TransformerFactory.newInstance();
Templates t = tf.newTemplates(new StreamSource(new File("stylesheet.xsl")));
StringWriter writer = new StringWriter();
t.newTransformer().transform(
 new StreamSource(new File("input.xml")), 
 new StreamResult(writer));

If all you are doing is changing the text of tags and attributes, not the structure of the XML file itself, then you can simply read it in as a text file and swap all instances of one string with another using Regex. The following code should get you started:

//read in the file one line at a time
BufferedReader in = new BufferedReader(new FileReader("input.xml"));
FileOutputStream fos = new FileOutputStream("output.xml");
try {

    StringBuilder sb = new StringBuilder();
    String l = "";
    String nl = System.getProperty("line.separator");

    //get next line, assign it to l, and make sure it exists. The line after the last in the file will always be null
    while((l = in.readLine()) != null) {
        //replace the desired substrings of each line
        if(l.contains("PrimeLineNo")) {
            l = l.replaceAll("PrimeLineNo", "LineNumber");
        }
        if(l.contains("SubLineNo")) {
            l = l.replaceAll("SubLineNo", "SubLineNumber");
        }
        //add the line to a string buffer to be written to file later
        sb.append(l + nl);
    }   

    //after we have gone through the entire input file, write it to the output file
    fos.write(sb.toString().getBytes());
}
catch(Exception e) {
    System.out.println("An unknown error occurred");
}
finally {
    //ensure the streams will always close
    in.close();
    fos.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM