我被困了我想要解析一个平铺的地图文件,并且有一个问题。我不知道如何获得x,y,width,height元素,以及如何重建这个xml。我将非常感谢你的帮助。
<objectgroup name="Meter">
<object type="meter" x="3232" y="6016" width="512" height="96">
<properties>
<property name="id" value="1"/>
</properties>
</object>
我的Java源代码:
public void readXml () throws ParserConfigurationException{
File fXmlFile = new File("xml1.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = null;
try {
doc = dBuilder.parse(fXmlFile);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
doc.getDocumentElement().normalize();
System.out.println(doc.toString());
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("objectgroup");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
System.out.println("\nCurrent Element :" + nNode.getAttributes().getNamedItem("meter"));
}}
答案 0 :(得分:0)
你必须进行一些调整,首先你必须遍历所有的孩子并获得所有的对象元素,然后得到他们的属性值,我知道这不是一个最佳的解决方案,但会得到你需要的东西:
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("objectgroup");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
// for that will go for all objectGroups
Node nNode = nList.item(temp);
NodeList childs = nNode.getChildNodes();
for (int i = 0; i < childs.getLength(); i++) {
Node child = childs.item(i);
if (child.getNodeName().equals("object")) {
// check if we are evaluating an <object> element
System.out.println("\nCurrent Element :"
+ child.getNodeName());
NamedNodeMap attrs = child.getAttributes();
Node x = attrs.item(3), y = attrs.item(4), height = attrs
.item(0), width = attrs.item(2), type = attrs
.item(1);
System.out.println("\n x :" + x.getNodeValue() + " | y : "
+ y.getNodeValue() + " | height: "
+ height.getNodeValue() + " | width: "
+ width.getNodeValue());
}
}
}