2013-06-24 26 views
5

Tôi đang chỉnh sửa tệp XML bằng Java bằng Trình biến đổi bằng cách thêm các nút khác. Mã XML cũ không thay đổi nhưng các nút XML mới có &lt;&gt; thay vì <> và nằm trên cùng một dòng. Làm cách nào để nhận được <> thay vì &lt;&gt; và cách tôi nhận được ngắt dòng sau các nút mới. Tôi đã đọc một số chủ đề tương tự nhưng không thể có được định dạng phù hợp. Dưới đây là phần có liên quan của mã:Đầu ra Biến áp Java < và > thay vì <>

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

Cảm ơn

+0

bạn có thể hiển thị đầu vào mẫu nhỏ và đầu ra mẫu nhỏ không? – Woot4Moo

+0

Không có đề cập đến '<' or '>' trong mã trên. Bạn tiêm chúng như thế nào? – fge

+0

Hãy cho chúng tôi một đầu mối! Hiển thị cho chúng tôi một số dấu ngoặc nhọn ... –

Trả lời

4

dựa trên một câu hỏi được đăng here:

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

sản xuất:

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

Sự khác biệt tôi thấy:

fDoc.setXmlStandalone(true); 
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 
1

Hãy thử đi qua InputStream thay vì Writer đến StreamResult.

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

Biến áp documentation cũng gợi ý điều đó.

5

Để thay thế & gt và các thẻ khác mà bạn có thể sử dụng org.apache.commons.lang3:

StringEscapeUtils.unescapeXml(resp.toString()); 

Sau đó bạn có thể sử dụng tài sản của biến sau đây để có ngắt dòng trong xml của bạn:

transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
Các vấn đề liên quan