简体   繁体   English

如何在java中将无效数据写入xml文件

[英]How to write invalid data to xml file in java

Is there any way to write below data to xml in java.有没有办法在java中将以下数据写入xml。 Please help me请帮我

<tag>  
   <abc="1"/>  
   <cde="a"/>  
   <xyz="3"/>  
</tag>  
  1. Create a file:创建一个文件:

    File file = new File(fileLocation);
    fileLocation= <Your_File_path>

  2. Create a file writer object:创建一个文件编写器对象:

    FileWriter generateXML=new FileWriter(file);

  3. You can write on the file like below:您可以在文件上写如下:

    generateXML.write("<tag>");

As an example...举个例子...

import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileOutputStream;

public class Foobar {

    public static void main(String[] args) throws Exception {
        /* one way */
        FileOutputStream fileOutputStream = new FileOutputStream(new File("/tmp/foobar.txt"));
        String data = "<tag>  \n" +
                "   <abc=\"1\"/>  \n" +
                "   <cde=\"a\"/>  \n" +
                "   <xyz=\"3\"/>  \n" +
                "</tag>  ";

        fileOutputStream.write(data.getBytes());

        /* another way */
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element tag = doc.createElement("tag");
        Attr abc = doc.createAttribute("abc");
        Attr cde = doc.createAttribute("cde");
        Attr xyz = doc.createAttribute("xyz");
        abc.setValue("1");
        cde.setValue("2");
        xyz.setValue("3");
        CDATASection cdataSection = doc.createCDATASection(makeInvalidTag(abc) + makeInvalidTag(cde) + makeInvalidTag(xyz));
        tag.appendChild(cdataSection);
        doc.appendChild(tag);
        StreamResult streamResult = new StreamResult(new File("/tmp/foobar2.txt"));
        DOMSource domSource = new DOMSource(doc);
        TransformerFactory.newInstance().newTransformer().transform(domSource, streamResult);
    }

    private static String makeInvalidTag(Attr attr) {
        return "\u003C" + attr.toString() + "/\u003E";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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