我的XML文件是這樣的:如何從xml文件中獲取屬性?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE pointList SYSTEM "point.dtd">
<pointList>
<point unit="mm">
<x>2</x>
<y>3</y>
</point>
<point unit="cm">
<x>9</x>
<y>3</y>
</point>
<point unit="px">
<x>4</x>
<y>7</y>
</point>
</pointList>
當我嘗試獲取標記點的屬性:
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class TryXml {
public static void main (String [] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
}
catch (ParserConfigurationException e){
System.out.println(e.getMessage());
}
File f = new File("p1.xml");
try {
doc=builder.parse(f);
}
catch (SAXException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
Element root = doc.getDocumentElement();
System.out.println(root.getTagName());
System.out.println("****************");
NodeList nList = root.getChildNodes();
for (int i=0;i<nList.getLength();i++) {
if(nList.item(i) instanceof Element)
System.out.println(nList.item(i).getAttributes());
}
}
}
我得到的是類似地址:
[email protected]
[email protected]
[email protected]
能任何人都會給我一個關於如何獲得點和其他內部標籤的屬性的提示?
但是,如果我使用「單位」我如何獲得內部標籤的值?我需要的結果是這樣的:'點23毫米,點93釐米,點47px' – Gipsy
你現在有'元素',並可以從那裏工作你的方式通過孩子:'((Element)nList.item(i)) .getChildNodes()'會爲你提供另一個'NodeList',通過它可以完全按照你在代碼中通過'nList'進行迭代。 – Oliver
@Gipsy在我的答案中看到編輯。 –