7

ノードを追加して、Transformer を使用して Java で XML ファイルを編集しています。古い XML コードは変更されていませんが、新しい XML ノードには <> の代わりに and があり、同じ行にあります&lt;。and&gt;の代わりに <> を取得する方法と、新しいノードの後に​​改行を取得する方法を教えてください。私はすでにいくつかの同様のスレッドを読みましたが、正しいフォーマットを取得できませんでした. コードの関連部分は次のとおりです。&lt;&gt;

// Read the XML file

DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();   
DocumentBuilder db = dbf.newDocumentBuilder();   
Document doc=db.parse(xmlFile.getAbsoluteFile());
Element root = doc.getDocumentElement();


// create a new node
Element newNode = doc.createElement("Item");

// add it to the root node
root.appendChild(newNode);

// create a new attribute
Attr attribute = doc.createAttribute("Name");

// assign the attribute a value
attribute.setValue("Test...");

// add the attribute to the new node
newNode.setAttributeNode(attribute);



// transform the XML
Transformer transformer = TransformerFactory.newInstance().newTransformer();   
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
StreamResult result = new StreamResult(new FileWriter(xmlFile.getAbsoluteFile()));   
DOMSource source = new DOMSource(doc);   
transformer.transform(source, result);

ありがとう

4

3 に答える 3

7

> およびその他のタグを置き換えるには、org.apache.commons.lang3 を使用できます。

StringEscapeUtils.unescapeXml(resp.toString());

その後、トランスフォーマーの次のプロパティを使用して、xml に改行を含めることができます。

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
于 2014-02-11T12:57:57.323 に答える
5

ここに投稿された質問に基づいて:

public void writeToOutputStream(Document fDoc, OutputStream out) throws Exception {
    fDoc.setXmlStandalone(true);
    DOMSource docSource = new DOMSource(fDoc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    transformer.transform(docSource, new StreamResult(out));
}

生成:

<?xml version="1.0" encoding="UTF-8"?>

私が見る違い:

fDoc.setXmlStandalone(true);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
于 2013-06-24T17:06:35.560 に答える
1

toInputStreamの代わりに渡してみてください。WriterStreamResult

StreamResult result = new StreamResult(new FileInputStream(xmlFile.getAbsoluteFile()));

Transformer のドキュメントもそれを示唆しています。

于 2013-06-24T17:12:49.493 に答える