1

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

2

You're currently asking for the typ attribute of the <Author> element (twice, for some reason). You should fetch the <phone> element (which you're already doing) and then ask for the typ attribute of that element, rather than the <Author> element.

Sign up to request clarification or add additional context in comments.

3 Comments

so i need one more loop with phone nodelist?
@sevdah: No, not necessarily - it depends on whether you're expecting more than one phone element. (Your current code only fetches one, so you could do the same thing here...)
one phone element for every author. Im not sure how to call getattribute method on that element....

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.