java:写入xml文件

时间:2011-05-30 14:36:33

标签: java xml xsd

在java中

我需要创建如下所示的xml文件:

<?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>

我在谷歌上找到了一些东西,但它与我的需求不符。因为我是java新手,我不知道如何根据我的需要调整它。

感谢您的帮助。

6 个答案:

答案 0 :(得分:2)

我建议你改用JAXB。创建类NikuDataBus,Header,CustomInformation等。将它们标记为@XmlEntity。创建和填充对象。

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)

答案 1 :(得分:1)

前一段时间我遇到了类似的问题,我使用的网站让我对不同的编码方式有了很好的理解。

This website 为您提供了许多不同的方法来编写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;

答案 2 :(得分:1)

我对XStream有过很好的体会。您只需创建对象并使用您想要的任何数据填充它们,最后只需xstream.toXML(object);即可获取xml的字符串。

答案 3 :(得分:0)

您的XML看起来像是基于XML架构(../xsd/nikuxog_customObjectInstance.xsd)。如果是这种情况,您可以使用XML Beans。给定XML Schema,XML Beans将生成一组Java类(或jar文件),您可以使用它们来创建XML。

优点是您的XML符合XML Schema。我发现这种方法在过去很有用,而且我对XML Bean有很好的经验。

答案 4 :(得分:0)

我这样解决了。这是糟糕的代码,但它适用于我,也许有一些由复制和粘贴引起的错误

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("");
    }
}

答案 5 :(得分:0)

您可以使用GitHub上提供的Scilca XML Progression包。

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");