gpt4 book ai didi

Java - 检索第二个元素 xml 文档 - DOM

转载 作者:行者123 更新时间:2023-11-30 03:24:51 24 4
gpt4 key购买 nike

如何在以下 xml-doc 中检索颜色元素及其属性

 <drawingobject>
<oval x="240" y="325" width="15" height="15" filled="yes">
<color r="0" g="255" b="255"></color>
</oval>
</drawingobject>

椭圆形的 dtd 看起来像这样

 <!-- elementet oval -->
<!ELEMENT oval (color?)>
<!ATTLIST oval x CDATA #REQUIRED>
<!ATTLIST oval y CDATA #REQUIRED>
<!ATTLIST oval width CDATA #REQUIRED>
<!ATTLIST oval height CDATA #REQUIRED>
<!ATTLIST oval filled (yes | no) "no">

我可以检索元素“oval”及其属性,但不知道如何测试它是否包含颜色元素和 IF - 检索它。

这是代码

 private void parse() throws Exception {

String docName = System.getProperty("user.home") + "/Desktop/" + "myxml.xml";
File file = new File(docName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
NodeList nodeList = document.getElementsByTagName("oval");
oval = new int[nodeList.getLength()][5];

for(int i= 0; i < nodeList.getLength(); i++) {

oval[i][0] = Integer.parseInt(nodeList.item(i).getAttributes().getNamedItem("x").getNodeValue());
oval[i][1] = Integer.parseInt(nodeList.item(i).getAttributes().getNamedItem("y").getNodeValue());
oval[i][2] = Integer.parseInt(nodeList.item(i).getAttributes().getNamedItem("width").getNodeValue());
oval[i][3] = Integer.parseInt(nodeList.item(i).getAttributes().getNamedItem("height").getNodeValue());

if (nodeList.item(i).getAttributes().getNamedItem("filled").getNodeValue().equals("yes")) {
oval[i][4] = 1;
} else {
oval[i][4] = 0;
}


Element ovalNode = (Element) nodeList.item(i);
NodeList colorNodes = ovalNode.getElementsByTagName("color");
if(colorNodes.getLength() > 0) {
System.out.println(colorNodes.item(i).getNodeName());
}

}

堆栈跟踪

 java.lang.NullPointerException
at test.parse(test.java:60)
at test.<init>(test.java:28)
at test.main(test.java:17)

System.out.println(colorNodes.item(i).getNodeName()); 位于第 60 行

最佳答案

与获取oval 元素的方法相同:使用Element.getElementsByTagName(String elementName)。您已经拥有要循环的 oval 元素,因此您只需在每个迭代元素上调用此方法即可:

for(int i= 0; i < nodeList.getLength(); i++) {
...

Element ovalNode = (Element) nodeList.item(i);
NodeList colorNodes = ovalNode.getElementsByTagName("color");
if(colorNodes.getLength() > 0) {
System.out.println(colorNodes.item(0).getNodeName()); // prints "color"
... // do something with the node
}
}

关于Java - 检索第二个元素 xml 文档 - DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30491623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com