我试图解析xml文件,但它不会打印attribut值。我不知道如何从手机获取属性典型
try { String subor = "Noviny.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(subor);
System.out.println("----------------\n");
NodeList nodelist = document.getElementsByTagName("Author");
NodeList nodelist1 = document.getElementsByTagName("Article");
for(int i = 0; i < nodelist.getLength(); i++) {
Node uzol = nodelist.item(i);
if (uzol.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) uzol;
System.out.println("Id:" + element.getElementsByTagName("Id").item(0).getTextContent() + "\n");
System.out.println("Name:" + element.getElementsByTagName("Name").item(0).getTextContent() + "\n");
System.out.println("Email:" + element.getElementsByTagName("Email").item(0).getTextContent() + "\n");
System.out.println("typ: " + element.getAttribute("typ") + "\n");
System.out.println("phone:" + element.getElementsByTagName("phone").item(0).getTextContent() + "\n");
System.out.println("typ: " + element.getAttribute("typ") + "\n");
System.out.println("sal: " + element.getElementsByTagName("sal").item(0).getTextContent() + "\n");
}
catch (Exception e) {
e.printStackTrace();
}
和xml
<Noviny>
<Author>
<Id>1</Id>
<Name>first</Name>
<Email>first@gmail.com</Email>
<phone typ="mobil">09443916565</phone>
<sal>500</sal>
</Author>
<Author>
<Id>2</Id>
<Name>second</Name>
<Email>second@gmail.com</Email>
<phone typ="pevna">094415665465</phone>
<sal>1000</sal>
</Author>
还有一件事:是否可以只打印(System.out.println)xml文件的树表示?
谢谢
答案 0 :(得分:1)
element
是Author
元素节点,没有属性。 typ
属性位于phone
标记
Element phone = (Element)element.getElementsByTagName("phone").item(0);
System.out.println("typ: " + phone.getAttribute("typ") + "\n");
对于第二部分,请尝试
Element root = document.getDocumentElement();
System.out.println(root.toString());