| Author |
Retrieve data from XML to java object
|
Angus Ferguson
Ranch Hand
Joined: Jun 22, 2012
Posts: 246
|
|
Hi I am trying a simple example. Extract values from XML to java objects.
My method is :
public NodeList getAllCompany( String companyName)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File("transfer.xml");
// if (file.exists()) {
Document doc = db.parse(file);
// Lectura de contenido en pantalla
Element docEle = doc.getDocumentElement();
// Print root element of the document
System.out.println("Root element of the document: "
+ docEle.getNodeName());
//The result is config
NodeList companyData = null;
companyData = docEle.getElementsByTagName("company");
System.out.println(companyData.item(0).getLocalName()+"*************************************************************************"); //The result is null
return companyData;
}
And my XML is called transfer.xml and is:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<companies>
<company>
<name>Pefere</name>
<baseUrl>1</baseUrl>
<startDate>01/02/2012</startDate>
<endDate>01/09/2012</endDate>
<dimensions>
<CityName>Boston</CityName>
<browser>Explorer</browser>
</dimensions>
<metrics>
<!-- Majorn than ... -->
<visits>3</visits>
</metrics>
<ids>1</ids>
<sorting></sorting>
<filters></filters>
</company>
</companies>
</config>
I have located the xml file in C:\home\tomcat\bin\transfer.xml
Any expert around?
Many Thanks,
|
 |
g tsuji
Ranch Hand
Joined: Jan 18, 2011
Posts: 368
|
|
DocumentBuilderFactory instance is default to namespace un-aware. In the case other than namespace aware, the local name of a node is not populated, and hence, null.
If for some reason you need to use getLocalName() to return a non-null result, you should add that setting explicitly immediately after the set up of DocumentBuilderFactory instance, otherwise, you can use getNodeName() for it or, in case the node is an element, cast it to its subclass Element and use getTagName() for it.
|
 |
Angus Ferguson
Ranch Hand
Joined: Jun 22, 2012
Posts: 246
|
|
Thanks for you reply I have learned from it, it works now. My XML was bad formed
Regards,
|
 |
Angus Ferguson
Ranch Hand
Joined: Jun 22, 2012
Posts: 246
|
|
Hi,
I have a new question about XML.The XML code is:
<company>
<dimension>
<visitor>
</visitor>
</dimension>
<metric>
<visitor>
</visitor>
</metric>
</company>
Using the XML PARSER object I can access to "dimesion", but after that I try acces to "metrics" but it launches an error(it doesn't find metric tag).
Any idea, please?
Many Thanks,
|
 |
Akhilesh Trivedi
Ranch Hand
Joined: Jun 22, 2005
Posts: 1493
|
|
Angus Ferguson wrote:Hi,
.
.
.
<metric>
<visitor>
</visitor>
</metric>
.
.
.
but after that I try acces to "metrics" but it launches an error(it doesn't find metric tag).
.
Is it "metric" or "metrics"?
|
Keep Smiling Always — My life is smoother when running silent. -paul
[FAQs] [Certification Guides] [The Linux Documentation Project]
|
 |
Angus Ferguson
Ranch Hand
Joined: Jun 22, 2012
Posts: 246
|
|
Hi,
I use metric in my XML and when I try t retrieve the value using getTagValue("metric", elemento)
Thanks
|
 |
Angus Ferguson
Ranch Hand
Joined: Jun 22, 2012
Posts: 246
|
|
Hi again, I have change somethings. This is my XML:
<company>
<!-- This field could be set dinamically and then from a JSP decide which company and which dates are needed-->
<name>companyName</name>
<baseUrl>TestURL</baseUrl>
<startDate>01/02/2012</startDate>
<endDate>01/09/2012</endDate>
<dimension>
<visitor>
<browser>true</browser>
</visitor>
</dimension>
<company>
I want access to my data in the XML, and this is my javaCode:
public Node getAllCompany(String fileName, String companyName)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);
// if (file.exists()) {
Document doc = db.parse(file);
// Transform the xml file in an object
Element docEle = doc.getDocumentElement();
NodeList companyData = null;
companyData = docEle.getElementsByTagName("company");
System.out.println(companyData .getLength()+"companyData .getLength()");
for (int temp = 0; temp < companyData .getLength(); ++temp) {
Node nNode = companyData.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element ecompanyData= (Element) nNode;
// System.out.println("visitor: " + getTagValue("visitor", eElement));
//Company Names
NodeList ecompanyNameList = ecompanyData.getElementsByTagName("name");
Element ecompanyNameElement = (Element)ecompanyNameList.item(0);
NodeList nameList = ecompanyNameElement.getChildNodes();
System.out.println("ecompanyNameElement: " +
((Node)nameList.item(0)).getNodeValue().trim());
//Company Dimension
NodeList ecompanyDimensionList = ecompanyData.getElementsByTagName("dimension");
Element ecompanyDimensionElement = (Element)ecompanyDimensionList.item(0);
NodeList dimensionList = ecompanyDimensionElement.getChildNodes();
System.out.println("ecompanyDimensionElement: " +
((Node)dimensionList.item(0)).getNodeValue().trim());
for (int i = 0; i < dimensionList.getLength(); i++) {
NodeList visitorDimensions= ecompanyDimensionElement.getElementsByTagName("visitor");
for(int j=0; j<visitorDimensions.getLength(); j++)
{
Element listDimension = (Element)visitorDimensions.item(j);
System.out.println("C ---- "+listDimension.getAttribute("browser"));
// NodeList recordFolders = listDimension.getElementsByTagName("rma:recordFolder");
}
// NodeList categories = serie.getElementsByTagName("dod:recordCategory")
//Company Visitor
}
}
It only retrieves company name, but nothing more. Any help please?
Many Thanks,
Cheers!
|
 |
Angus Ferguson
Ranch Hand
Joined: Jun 22, 2012
Posts: 246
|
|
Hi, using the code which I have posted before when I ask fo dimension length I got 23 but is not 23 childs
Any idea, please?
Thanks
|
 |
g tsuji
Ranch Hand
Joined: Jan 18, 2011
Posts: 368
|
|
I suggest you use all along getElementsByTagName() if that method you understand better. It also flattens the hierarchical structure so that you can use for instance ecompanyData to get to "visitor" or other more obvious simple Elements directly. That simplifies the algorithm. Then you can use getTextContent() to get the text data you need.
The problem also is that getChildNodes() get literally Element as well as Text nodes. That is why you have to code further conditional to verify a node's type is ELEMENT_NODE before going to lower levels...
Read serious tutorials and practice their examples are more efficient in learning and you form less wrong concepts/impressions by pure imagination during trial and error.
|
 |
 |
|
|
subject: Retrieve data from XML to java object
|
|
|