我一直在努力学习一些使用Java解析文件的新技术,而在msot方面进展顺利。但是,我不知道如何将xml文件解析为收据后未知的结构。如果您知道结构(getElementByTagName似乎是行之有效的方法)的话,有很多示例,但是没有动态选项,至少我没有发现。
因此,这个问题的tl; dr版本如何在我不依赖于知道其结构的情况下如何解析xml文件?
解析部分很容易;就像注释中所述的holderdarocha一样,解析器仅需要有效的XML,而不关心结构。您可以使用Java的标准DocumentBuilder
来获取Document
:
InputStream in = new FileInputStream(...);
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
(如果要解析多个文档,则可以继续重复使用同一文档DocumentBuilder
。)
然后,您可以从根文档元素开始,然后使用熟悉的DOM方法:
Element root = doc.getDocumentElement(); // perform DOM operations starting here.
至于处理它,这实际上取决于您要处理的内容,但是您可以使用Node
like的方法,getFirstChild()
并getNextSibling()
根据结构,标签和属性的合适情况遍历子项和进程。
考虑以下示例:
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class XML {
public static void main (String[] args) throws Exception {
String xml = "<objects><circle color='red'/><circle color='green'/><rectangle>hello</rectangle><glumble/></objects>";
// parse
InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
// process
Node objects = doc.getDocumentElement();
for (Node object = objects.getFirstChild(); object != null; object = object.getNextSibling()) {
if (object instanceof Element) {
Element e = (Element)object;
if (e.getTagName().equalsIgnoreCase("circle")) {
String color = e.getAttribute("color");
System.out.println("It's a " + color + " circle!");
} else if (e.getTagName().equalsIgnoreCase("rectangle")) {
String text = e.getTextContent();
System.out.println("It's a rectangle that says \"" + text + "\".");
} else {
System.out.println("I don't know what a " + e.getTagName() + " is for.");
}
}
}
}
}
输入的XML文档(例如,硬编码)为:
<objects>
<circle color='red'/>
<circle color='green'/>
<rectangle>hello</rectangle>
<glumble/>
</objects>
输出为:
这是一个红色的圆圈! 这是一个绿色的圆圈! 这是一个矩形,上面写着“你好”。 我不知道这是什么意思。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句