我的xml为String
<color>
<name>black</name>
<color>
我想向root节点添加一个属性,并再次将xml保存为String。
<color id="1">
<name>black</name>
<color>
但我不能。这是我的代码
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.InputSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
String xml = "<color><name>black</name></color>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document document = builder.parse(is);
Element element = (Element) document.getFirstChild();
element.setAttribute("id", "1");
String result = document.toString();
System.out.println(result);
输出为[#document:null]。帮帮我解决我的问题
答案 0 :(得分:1)
您不能使用document.toString()来获取输出。您需要将文档对象转换回xml字符串。 请检查以下代码。它将有助于解决您的问题。
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class test1 {
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException {
final String xmlStr = "<color><name>black</name></color>";
Document doc = convertStringToDocument(xmlStr);
String str = convertDocumentToString(doc);
System.out.println(str);
}
private static Document convertStringToDocument(String xmlStr)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlStr));
Document document = builder.parse(is);
Element element = (Element) document.getFirstChild();
element.setAttribute("id", "1");
String result = document.toString();
System.out.println(result);
return document;
}
private static String convertDocumentToString(Document doc) {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
}