0

我试图解析 xml 文件,但它不会打印属性值。我不知道如何从手机获取属性类型

 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>

还有一件事:ň是否可以只打印 xml 文件的 (System.out.println) 树表示?

谢谢你

4

1 回答 1

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());
于 2013-05-01T01:44:18.710 回答