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

时间:2015-09-09 11:11:04

标签: java xml xml-parsing

有没有办法在java中将下面的数据写入xml。请帮帮我

<tag>  
   <abc="1"/>  
   <cde="a"/>  
   <xyz="3"/>  
</tag>  

2 个答案:

答案 0 :(得分:0)

  1. 创建文件:

    .asp

  2. 创建文件编写器对象:

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

  3. 您可以在以下文件中书写:

    FileWriter generateXML=new FileWriter(file);

答案 1 :(得分:0)

作为一个例子......

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