0

im trying to parse xml file, but it wont print attribut value. I dont know how to get attribute typ from phone

 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();
}

and xml

<Noviny>
  <Author>
    <Id>1</Id>
    <Name>first</Name>
    <Email>[email protected]</Email>
    <phone typ="mobil">09443916565</phone>  
    <sal>500</sal>
  </Author>
  <Author>
    <Id>2</Id>
    <Name>second</Name>
    <Email>[email protected]</Email>
    <phone typ="pevna">094415665465</phone>  
    <sal>1000</sal>
  </Author>

and one more thing:ňIs it possible to just print (System.out.println) tree representation of xml file?

thank you

1 Answer 1

1

element is a Author element node and has no attributes. The typ attribute is on the phone tag

Element phone = (Element)element.getElementsByTagName("phone").item(0);
System.out.println("typ: " + phone.getAttribute("typ") + "\n");

For the second part, try

Element root = document.getDocumentElement();
System.out.println(root.toString());
Sign up to request clarification or add additional context in comments.

1 Comment

I tried that, but I got error: cannot find symbol - method getAttribure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.