0

I have the following code:

<ishfields>
    <ishfield name="FTITLE" level="logical">3* Family map</ishfield>
    <ishfield name="FDESCRIPTION" level="logical">111</ishfield>
    <ishfield name="FCHANGES" level="version" />
</ishfields>

I want to get the text content of field name="FDESCRIPTION".

i am not even able to fetch the content 111.

I have used getelementsbytagname() and many approaches. Can anyone help how to do this? here is my java code:

try {

String file="E:\\Repository\\17Nov_demo\\file.xml";
DocumentBuilderFactory documentbuilderfactory=DocumentBuilderFactory.newInstance();
DocumentBuilder documentbuilder =documentbuilderfactory.newDocumentBuilder();
Document doc=documentbuilder.parse(file);

Element element=doc.getDocumentElement();
NodeList nodelist=element.getChildNodes();
for (int i = 0; i < nodelist.getLength(); i++) {
    System.out.println(nodelist);
}

}
catch(Exception e)
{

}

i know it will only fetch the entire document nodes. But i cannot understand how to go to that particular node uing xpath or whatever. please help!!

srishti
  • 23
  • 1
  • 1
  • 9

2 Answers2

0

If you do many things with Xml, prefer xPath than native code much more readable.

And for retrieve your data you just need to do :

//ishfield[@name="FDESCRIPTION"]/text()

You can test here :

http://www.xpathtester.com/xpath/7f3c6f31096fbb33c728ca3e6216fd41

Gegko

Gegko
  • 15
  • 4
0

You can use JAXB. You can see what JAXB is here.

Now you have to specify the ishfields class in java for example like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="ishfields")
class Ishfields{
    List<Ishfield> fields;
}

and of course the Ishfield class:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="ishfield")
class Ishfield{
    @XmlAttribute
    String name;
    @XmlAttribute
    String level;    
}

Now in the Main class you can try this:

import java.io.FileReader;
import java.util.List;

import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
//those are the all the imports you need. You can import all of them in Main if you also put here the two classes as inner.
public class Main {

    public static void main(String[] args) throws Exception {
        Ishfields i = JAXB.unmarshal(new FileReader("yourXml.xml"), Ishfields.class);
        System.out.println(r);
        JAXB.marshal(r, System.out);
    }
}

And also you can do whatever you want with the generated object. You can get value, name, level and so on. I am asuming that your xml is in a file. There are ways of course to do the same thing if your xml is a String.

Community
  • 1
  • 1
Lazar Lazarov
  • 2,412
  • 4
  • 26
  • 35