我试图解析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 :(得分:2)
您目前要求typ
元素的<Author>
属性(由于某种原因,两次)。您应该获取<phone>
元素(您已经在做的事情),然后要求那个元素的typ
属性,而不是<Author>
元素。