0

我有一个要转换为 xml 的字符串列表。我将如何使用 DOM 来做到这一点?我不确定如何使用字符串创建文档以用作Source生成 XML。

谁能给我看一个生成文档的示例代码?例如,XML 如下:

ArrayList<String> fruits

<Fruits>
  <fruit>Apple<fruit>
  <fruit>Grape<fruit>
<Fruits>

我认为代码将是:

TransformerFactory transFact = TransformerFactory.newInstance();
Transformer serializer = transFact.newTransformer();
Properties props = new Properties();
props.put("method", "xml");
props.put("indent", "yes");
serializer.setOutputProperties(props);
Source source = new DOMSource(document); //need to create a document
Result result = new StreamResult(PrintWriter);  
4

3 回答 3

3
    ArrayList<String> a = new ArrayList<String>();
    a.add("apple"); a.add("mango");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    Document doc = docBuilder.newDocument();
    Element root = doc.createElement("Fruits");
    doc.appendChild(root);

    for(String name: a){
        Element fruit = doc.createElement("fruit");
        fruit.appendChild(doc.createTextNode(name)); 
        root.appendChild(fruit);
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("C:\\file.xml"));

    transformer.transform(source, result);
于 2012-11-19T15:08:12.267 回答
1

我会为此使用 JAXB:

@XmlRootElement(name = "Fruits")
@XmlAccessorType(XmlAccessType.FIELD)
public static class Fruits
{
    @XmlElement(name = "fruit")
    public List<String> fruit = new ArrayList<String>();
}

public static void main(String[] args) throws Exception
{
    Fruits fruits = new Fruits();
    fruits.fruit.add("Apple");
    fruits.fruit.add("Grape");

    TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer serializer = transFact.newTransformer();
    Properties props = new Properties();
    props.put("method", "xml");
    props.put("indent", "yes");
    serializer.setOutputProperties(props);
    Source source = new JAXBSource(JAXBContext.newInstance(Fruits.class), fruits);
    Result result = new StreamResult(System.out);
    serializer.transform(source, result);
}
于 2012-11-19T15:07:32.633 回答
0

如果您真的想使用“fruits”列表中的字符串作为源创建文档:

    StringBuilder sb  = new StringBuilder();
    for(String s : fruits) {
        sb.append(s).append('\n');
    }
    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    Document doc = f.newDocumentBuilder().parse(new InputSource(new StringReader(sb.toString())));
于 2012-11-19T15:10:31.227 回答