skaryu
skaryu

Reputation: 141

java: write to xml file

in java I need to create xml file which look like this:

<?xml version="1.0" encoding="UTF-8"?>
<NikuDataBus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../xsd/nikuxog_customObjectInstance.xsd">
    <Header action="write" externalSource="NIKU" objectType="customObjectInstance" version="8.1.0.4247"/>
    <customObjectInstances objectCode="hen_allockey_p">
        <instance instanceCode="MIG5033028" objectCode="hen_allockey_p"
        parentInstanceCode="001260" parentObjectCode="project">
            <CustomInformation>
                <ColumnValue name="hen_from">200801</ColumnValue>
                <ColumnValue name="name">MIG5033028</ColumnValue>
                <ColumnValue name="code">MIG5033028</ColumnValue>
            <OBSAssocs/>
            <Security/>
        </instance>
    </customObjectInstances>
</NikuDataBus>

I found something on google, but it didn't match to my needs. And as I am new with java, I don't know how to adapt it to my needs.

Thank you for your help.

Upvotes: 0

Views: 3555

Answers (6)

Shukant Pal
Shukant Pal

Reputation: 730

You can use the Scilca XML Progression package available at GitHub.

Node rootNode = Node.constructNode(<NikuDataBusxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../xsd/nikuxog_customObjectInstance.xsd">");

rootNode.addChildNode(Node.constructNode("<Header action="write" externalSource="NIKU" objectType="customObjectInstance" version="8.1.0.4247"/>"));

String customObj = "<customObjectInstances objectCode="hen_allockey_p">" 
                        + "<instance instanceCode="MIG5033028" objectCode="hen_allockey_p" parentInstanceCode="001260" parentObjectCode="project">" 
                        + "<CustomInformation>"
                              + "<ColumnValue name="hen_from">200801</ColumnValue>"
                              + "<ColumnValue name="name">MIG5033028</ColumnValue>"
                              + "<ColumnValue name="code">MIG5033028</ColumnValue>"
                        + "</CustomInformation>"
                        + "<OBSAssocs/><Security/>"
                        + "</instance>"
                        + "</customObjectInstances>"

  // Now build to customObject element using a VirtualXML Iterator

 XMLIterator xi = new VirtualXML.XMLIterator(customObj);
 Node customO = Node.readFromFile(xi);

 rootNode.addChildNode(customO);

 Document XmlDocument = new Document(rootNode);
 XmlDocument.addXmlDeclaration(1.0, "UTF-8", null);

 XMLWriter xw = XmlDocument.getWriter();
 xw.write("D:/file.txt");

Upvotes: 0

skaryu
skaryu

Reputation: 141

I resolved it like this. It is bad looking code, but it works for me, maybe there are some errors caused by copy and paste

public class POIExcelReader {

private void setHenAllocKeyHeader(StringBuilder sb) {
    sb.append ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
            + "<NikuDataBus xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"../xsd/nikuxog_customObjectInstance.xsd\">\r\n"
            + "<Header action=\"write\" externalSource=\"NIKU\"objectType=\"customObjectInstance\" version=\"8.1.0.4247\"/>\r\n"
            + "<customObjectInstances objectCode=\"hen_allockey_p\">\r\n"
            + "<instance instanceCode=\"MIG5033028\" objectCode=\"hen_allockey_p\" parentInstanceCode=\"001260\" parentObjectCode=\"project\">\r\n");
}

private void setHenAllocKeyBottom (StringBuilder sb) {
    sb.append ("<OBSAssocs/>\r\n"
            +"<Security/>\r\n"
            +"</customObjectInstances>\r\n" 
            + "</NikuDataBus>\r\n");
}

protected void jobRun() throws Exception {

    StringBuilder sb = new StringBuilder();
    setHenAllocKeyHeader(sb);
    String prolog = sb.toString();

    sb = new StringBuilder();
    setHenAllocKeyBottom(sb);
    String epilog = sb.toString();


    FileOutputStream fos = new FileOutputStream("c:\\test\\osem.xml");
    OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.forName("UTF-8"));
    osw.write(prolog);
    osw.write(epilog);
    osw.flush();
    osw.close();

}
public static void main(String[] args){
try{
            job.jobRun();
    } catch (Exception e)
    {
        System.out.println("");
    }
}

Upvotes: 0

MarcoS
MarcoS

Reputation: 13564

It looks like your XML is based on an XML Schema (../xsd/nikuxog_customObjectInstance.xsd). If this is the case you can use XML Beans. Given the XML Schema, XML Beans will produce a set of Java classes (or a jar file) that you can use to create your XML progtrammatically.

The advantage is that your XML is compliant with your XML Schema. I found this approach useful in the past, and I have good experience with XML Beans.

Upvotes: 0

RMT
RMT

Reputation: 7070

I had a similar problem a while ago and the website i used that gave me a good understanding of differnt ways to code it is.

This website provides you many different ways to code the xml: String, DOM, SAX

TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        //create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        String xmlString = sw.toString();

        //Writing the string to a file
        OutputStream outputStream;
        byte buf[] = xmlString.getBytes();
        outputStream = new FileOutputStream(file);
        for (byte element : buf) {
            outputStream.write(element);
        }
        outputStream.close();
        buf = null;

Upvotes: 1

Kevin Jalbert
Kevin Jalbert

Reputation: 3245

I've had good experiences with XStream. You just make the objects and populate them with whatever data you want, and finally you just xstream.toXML(object); to get the string of the xml.

Upvotes: 1

AlexR
AlexR

Reputation: 115338

I'd suggest you to use JAXB instead. Create classes NikuDataBus, Header, CustomInformation etc. Mark them as @XmlEntity. Create and populate objects.

NikyDataBus dataBus = new NikuDataBus();
dataBus.setHeader(....)
//etc, etc....

File f = new File("mydata.xml");
Marshaller m = JAXBContext.newInstance(NikuDataBus.class, Header.class, CustomInformation.class ).createMarshaller().marshal(dataBus, f)

Upvotes: 2

Related Questions