Bạn nói đúng, với các API XML tiêu chuẩn, có không phải là một cách tốt - đây là một ví dụ (có thể lỗi cưỡi; nó chạy, nhưng tôi đã viết nó từ lâu rồi).
import javax.xml.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import java.io.*;
public class Proc
{
public static void main(String[] args) throws Exception
{
//Parse the input document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("in.xml"));
//Set up the transformer to write the output string
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
//Find the first child node - this could be done with xpath as well
NodeList nl = doc.getDocumentElement().getChildNodes();
DOMSource source = null;
for(int x = 0;x < nl.getLength();x++)
{
Node e = nl.item(x);
if(e instanceof Element)
{
source = new DOMSource(e);
break;
}
}
//Do the transformation and output
transformer.transform(source, result);
System.out.println(sw.toString());
}
}
Có vẻ như bạn có thể có được đứa con đầu lòng chỉ bằng cách sử dụng doc.getDocumentElement(). GetFirstChild(), nhưng vấn đề với điều đó là nếu có bất kỳ khoảng trắng giữa rễ và phần tử con, rằng sẽ tạo ra một nút văn bản trong cây, và bạn sẽ nhận được nút đó thay vì nút phần tử thực tế. Kết quả của chương trình này là:
D:\home\tmp\xml>java Proc
<?xml version="1.0" encoding="UTF-8"?>
<element1>
<child attr1="blah">
<child2>blahblah</child2>
</child>
</element1>
Tôi nghĩ bạn có thể chặn chuỗi phiên bản xml nếu bạn không cần, nhưng tôi không chắc chắn về điều đó. Tôi có lẽ sẽ cố gắng sử dụng một thư viện XML của bên thứ ba nếu có thể.
Nguồn
2009-03-10 21:04:09
Không, tôi muốn làm điều này với dom4j. ANy gợi ý ... – user234194