I have this xml file that contains 3 categories:employee_list, position_details and employee_info.
<?xml version="1.0" encoding="UTF-8"?>
<employee>
<employee_list>
<employee ID="1">
<firstname>Andrei</firstname>
<lastname>Rus</lastname>
<age>23</age>
<position-skill ref="Java"/>
<detail-ref ref="AndreiR"/>
</employee>
<employee ID="2">
<firstname>Ion</firstname>
<lastname>Popescu</lastname>
<age>25</age>
<position-skill ref="Python"/>
<detail-ref ref="IonP"/>
</employee>
<employee ID="3">
<firstname>Georgiana</firstname>
<lastname>Domide</lastname>
<age>33</age>
<position-skill ref="C"/>
<detail-ref ref="GeorgianaD"/>
</employee>
</employee_list>
<position_details>
<position ID="Java">
<role>Junior Developer</role>
<skill_name>Java</skill_name>
<experience>1</experience><!-- years of experience -->
</position>
<position ID="Python">
<role>Developer</role>
<skill_name>Python</skill_name>
<experience>3</experience>
</position>
<position ID="C">
<role>Senior Developer</role>
<skill_name>C</skill_name>
<experience>5</experience>
</position>
</position_details>
<employee_info>
<detail ID="AndreiR">
<username>AndreiR</username>
<residence>Timisoara</residence>
<yearOfBirth>1999</yearOfBirth>
<phone>0</phone>
</detail>
<detail ID="IonP">
<username>IonP</username>
<residence>Timisoara</residence>
<yearOfBirth>1997</yearOfBirth>
<phone>0</phone>
</detail>
<detail ID="GeorgianaD">
<username>GeorgianaD</username>
<residence>Arad</residence>
<yearOfBirth>1989</yearOfBirth>
<phone>0</phone>
</detail>
</employee_info>
</employee>
I would like to write java code for all 3 categories, but so far I have only managed to get past the first category (employee_list). When I try to retrieve information from the position_list or employee_info category, the program fails to find information according to each category.
I wrote the Java code for the 3 categories and the result looks like this:
package Dom;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
try {
File xmlDoc = new File("employees.xml");
DocumentBuilderFactory dbFact = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuild = dbFact.newDocumentBuilder();
Document doc = dBuild.parse(xmlDoc);
//Citim radacina
// doc localizeaza radacina da numele ei
System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
System.out.println("-----------------------------------------------------------------------------");
//citim un array de studenti pe care il denumim NodeList
NodeList nList = doc.getElementsByTagName("employee");
System.out.println("Total Category inside = " + nList.getLength());
System.out.println("-----------------------------------------------------");
for(int i = 0 ; i<nList.getLength();i++) {
Node nNode = nList.item(i);
//System.out.println("Node name: " + nNode.getNodeName()+" " + (i+1));
if(nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Person id#: " + eElement.getAttribute("id"));
System.out.println("Person Last Name: " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Person First name: " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Person Age: " + eElement.getElementsByTagName("age").item(0).getTextContent());
System.out.println("--------------------------------------------------------------------------");
}
}
System.out.println("=============================================================================================");
nList = doc.getElementsByTagName("position");
System.out.println("Total Category inside = " + nList.getLength());
System.out.println("-----------------------------------------------------");
for(int i = 0 ; i<nList.getLength();i++) {
Node nNode = nList.item(i);
//System.out.println("Node name: " + nNode.getNodeName()+" " + (i+1));
if(nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Role: " + eElement.getElementsByTagName("role").item(0).getTextContent());
System.out.println("Skill: "+ eElement.getElementsByTagName("skill_name").item(0).getTextContent());
System.out.println("Experience: "+ eElement.getElementsByTagName("experience").item(0).getTextContent());
System.out.println("--------------------------------------------------------------------------");
}
}
System.out.println("=============================================================================================");
nList = doc.getElementsByTagName("detail");
System.out.println("Total Category inside = " + nList.getLength());
System.out.println("-----------------------------------------------------");
for(int i = 0 ; i<nList.getLength();i++) {
Node nNode = nList.item(i);
//System.out.println("Node name: " + nNode.getNodeName()+" " + (i+1));
if(nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Person with username: " + eElement.getElementsByTagName("username").item(0).getTextContent());
System.out.println("Username: " + eElement.getElementsByTagName("username").item(0).getTextContent());
System.out.println("Residence: "+ eElement.getElementsByTagName("residence").item(0).getTextContent());
System.out.println("Year of birth: "+ eElement.getElementsByTagName("yearOfBirth").item(0).getTextContent());
System.out.println("Phone: "+ eElement.getElementsByTagName("phone").item(0).getTextContent());
System.out.println("--------------------------------------------------------------------------");
}
}
}catch(Exception e) {
}
}
}
output:
Root element: employee
-----------------------------------------------------------------------------
Total Category inside = 4
-----------------------------------------------------
Person id#:
Person Last Name: Rus
Person First name: Andrei
Person Age: 23
--------------------------------------------------------------------------
Person id#:
Person Last Name: Rus
Person First name: Andrei
Person Age: 23
--------------------------------------------------------------------------
Person id#:
Person Last Name: Popescu
Person First name: Ion
Person Age: 25
--------------------------------------------------------------------------
Person id#:
Person Last Name: Domide
Person First name: Georgiana
Person Age: 33
--------------------------------------------------------------------------
=============================================================================================
Total Category inside = 3
-----------------------------------------------------
Role: Junior Developer
Skill: Java
Experience: 1
--------------------------------------------------------------------------
Role: Developer
Skill: Python
Experience: 3
--------------------------------------------------------------------------
Role: Senior Developer
Skill: C
Experience: 5
--------------------------------------------------------------------------
=============================================================================================
Total Category inside = 3
-----------------------------------------------------
Person with username: AndreiR
Username: AndreiR
Residence: Timisoara
Year of birth: 1999
Phone: 0
--------------------------------------------------------------------------
Person with username: IonP
Username: IonP
Residence: Timisoara
Year of birth: 1997
Phone: 0
--------------------------------------------------------------------------
Person with username: GeorgianaD
Username: GeorgianaD
Residence: Arad
Year of birth: 1989
Phone: 0
--------------------------------------------------------------------------
Is there any possibility that the output could be slightly more grouped, in the following form for each person:
PersonId
firstname
lastname
age
role
skill_name
experience
username
residence
yearOfBirth
phone
But you've basically done it already, you wrote the code for the three categories. "Failing to find information according to each category" might mean that the output is not the desired output. The reason could be that Document.getElementsByTagName() searches globally for all elements that have the name passed as the argument. As your root element too is named employee, it's included as an additional Node in your NodeList on doc.getElementsByTagName("employee"), which btw. doesn't have an ID attribute of it's own (note: these are case-sensitive). Hence a "Total Category inside = 4". If you then do getElementsByTagName("lastname") on this first Node/Element that's the root, sure enough, it has a <lastname/> element below it, just not as a direct child, but two levels down, the element of the first "actual"/desired <employee/>.
So what you probably want to do is to not search for your element names globally, but in the local context of the category, as you already do successfully elsewhere inside the loops. Maybe just change
NodeList nList = doc.getElementsByTagName("employee");
to
NodeList nList = doc.getElementsByTagName("employee_list");
nList = ((Element)nList.item(0)).getElementsByTagName("employee");
for the employee_list category, and likewise for the other categories.
In order to group records more nicely, you don't need to output/print them immediately. You can copy/store the values you get from the DOM in the members of an object of a class you could define, or make a more generic class which stores the field values in a List that contains a Map, or something like that. With such, you can iterate/loop over the objects or list you created, and output/print the field values in your preferred order.
How can I extract value of more than one attribute node via XPath expression?
A sample XML file is:
<tag1>
<tag2>
<tag3 id="1">
<tage4>
<tage4code code="1">
<tag5>
<tage4Value Day="14" Month="Oct" Year="2000" />
</tag5>
<tag5>
<tage4Value Month="Oct" Year="2001" />
</tag5>
<tag5>
<tage4Value Year="2002" />
</tag5>
<tag5>
<tage4Value Day="1" Month="Jan" Year="1999" />
</tag5>
<tag5>
<tage4Value Year="1940" />
</tag5>
</tage4code>
</tage4>
</tag3>
</tag2>
</tag1>
So far I have this XPath string:
XPathExpression expr = xpath.compile("concat((/tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value/#Day, '/' , /tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value/#Month, '/', /tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value/#Year)");
NodeList combination1 = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int a = 0; a <= combination1.getLength(); a++) {
System.out.println("date : " + combination.item(a).getNodeValue());
}
My Expected result
14/Oct/2000
Oct/2001
2002
1/Jan/1999
1940
Can someone help to correct my XPathExpression
XPath 2.0 solution :
tokenize(replace(replace(replace(substring-after(string-join(//tag5/*|//tag5//#*,","),","),",,","%"),","," ")," ","/"),"%")
Output :
String='14/Oct/2000'
String='Oct/2001'
String='2002'
String='1/Jan/1999'
String='1940'
XPath 1.0 solution :
concat(translate(normalize-space(concat((//tage4Value)[1]/#Day," ",(//tage4Value)[1]/#Month," ",(//tage4Value)[1]/#Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[2]/#Day," ",(//tage4Value)[2]/#Month," ",(//tage4Value)[2]/#Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[3]/#Day," ",(//tage4Value)[3]/#Month," ",(//tage4Value)[3]/#Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[4]/#Day," ",(//tage4Value)[4]/#Month," ",(//tage4Value)[4]/#Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[5]/#Day," ",(//tage4Value)[5]/#Month," ",(//tage4Value)[5]/#Year))," ","/"))
Output :
String='14/Oct/2000|Oct/2001|2002|1/Jan/1999|1940'
Or with new line separator :
concat(translate(normalize-space(concat((//tage4Value)[1]/#Day," ",(//tage4Value)[1]/#Month," ",(//tage4Value)[1]/#Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[2]/#Day," ",(//tage4Value)[2]/#Month," ",(//tage4Value)[2]/#Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[3]/#Day," ",(//tage4Value)[3]/#Month," ",(//tage4Value)[3]/#Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[4]/#Day," ",(//tage4Value)[4]/#Month," ",(//tage4Value)[4]/#Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[5]/#Day," ",(//tage4Value)[5]/#Month," ",(//tage4Value)[5]/#Year))," ","/"))
Output :
String='14/Oct/2000
Oct/2001
2002
1/Jan/1999
1940'
This xpath expression
//tag3[#id="1"]//tage4code[#code=1]//tag5/tage4Value/concat(#Day,'/',#Month,'/',#Year)
should output
14/Oct/2000
/Oct/2001
//2002
1/Jan/1999
//1940
This way we can create a dynamic way of reading the child.
xpathExpression = "count(//tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value)";
double nodeList1 = (double) xpath.compile(xpathExpression).evaluate(doc, XPathConstants.NUMBER);
int s = (int) (nodeList1);
for (int z = 1; z <= s; z++) {
xpathExpression = "normalize-space(concat((//tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value)["
+ z
+ "]/#Day,\" \",(//tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value)["
+ z
+ "]/#Month,\" \",(//tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value)["
+ z + "]/#Year))";
String year = (String) xpath.evaluate(xpathExpression, doc, XPathConstants.STRING);
System.out.println(year);
}
I believe this is a simple question but I am having trouble to find out how it works.
That's the XML file (from www.w3schools.com):
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
As you can see the book XQuery Kick Start has more than one author.
But I cant find a way to get the right number of authors.
Thats my code:
public static void main(String argv[]) throws ParserConfigurationException, SAXException, IOException {
File fXmlFile = new File("\books.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("book");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Category : " + eElement.getAttribute("category"));
System.out.println("Title : " + eElement.getElementsByTagName("title").item(0).getTextContent());
System.out.println("Author : " + eElement.getElementsByTagName("author").item(0).getTextContent());
System.out.println("Year : " + eElement.getElementsByTagName("year").item(0).getTextContent());
System.out.println("Price : " + eElement.getElementsByTagName("price").item(0).getTextContent());
}
}
But as Result I'll be getting only one author:
Root element :bookstore
----------------------------
Current Element :book
Categoria do Livro : cooking
Titulo : Everyday Italian
Autor : Giada De Laurentiis
Ano : 2005
Price : 30.00
Current Element :book
Categoria do Livro : children
Titulo : Harry Potter
Autor : J K. Rowling
Ano : 2005
Price : 29.99
Current Element :book
Categoria do Livro : web
Titulo : XQuery Kick Start
Autor : James McGovern
Ano : 2003
Price : 49.99
Current Element :book
Categoria do Livro : web
Titulo : Learning XML
Autor : Erik T. Ray
Ano : 2003
Price : 39.95
Does anyone knows a good method to get the right number of elements?
sorry about the long question, I didnt know how to express myself so I had to paste here
*I'm new to DOM*
You're are getting the first author always, as you're retrieving the first item of the nodelist
getElementsByTagName("author").item(0)
Try iterating them, as there could be more than one
for (int i = 0; i < eElement.getElementsByTagName("author").getLength(); i++)
System.out.println("Author : " +
eElement.getElementsByTagName("author").item(i).getTextContent());
I have one module which consumes a webservice and fetches a response from it. The response which I am getting contains a value inside it on which I need to set it value. I am using XPath for that. Now when I am running this functionality on my local system I am getting the desired output, but when I am using that in my ear, it's not working.
The code in ear:
private static String stResponsePath="//Envelope//Body//AddNoteResponse//Response//";
private static String Fault_Path="//Envelope/Body/Fault/detail/CSIApplicationException/ServiceProviderEntity/";
/**
* Construct AddNoteResponse bean from
*
* #param addNote response SOAP XML
*/
public AddNoteResponse createAddNoteResponseFromSoapString(String soapString)throws EDDSystemException
{
try
{
Document soapDocument =AddNoteDomParserHelper.convertStringToDoc(soapString);
// EDDLog.outLog.info("soapDocument " + soapDocument.getFirstChild());
// EDDLog.outLog.info("soapDocument " + soapDocument.getLastChild());
EDDLog.outLog.info("soapString :" +soapString );
AddNoteResponse addNoteResponse= new AddNoteResponse();
addNoteResponse.setCode(AddNoteDomParserHelper.**getElementValue**(stResponsePath + "code", soapDocument));
addNoteResponse.setDescription(AddNoteDomParserHelper.**getElementValue**(stResponsePath + "description", soapDocument));
} .....
.....
}
public static String **getElementValue**(String elementName, Document doc) throws Exception
{
String value = "";
XPath xPath = XPathFactory.newInstance().newXPath();
if(xPath ==null)
{
EDDLog.outLog.info(" xpath is null");
}
EDDLog.outLog.info("doc " + doc.getFirstChild());
NodeList docNodes = (NodeList) xPath.evaluate(elementName,doc, XPathConstants.NODESET);
// NodeList docNodes = (NodeList) xPath.evaluate("/Envelope/Body/AddNoteResponse/Response/code",doc, XPathConstants.NODESET);
EDDLog.outLog.info("elementName :" +elementName );
//NodeList docNodes = doc.getElementsByTagNameNS("*", elementName);
if (docNodes == null || docNodes.getLength() == 0) {
docNodes = doc.getElementsByTagName(elementName);
EDDLog.outLog.info("docNodes.getLength() :"+docNodes.getLength());
}
Output of this is:
11 Jun 2013 13:47:40,644 INFO soapString :<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header> <MessageHeader xmlns:cng="http://csi.cingular.com/CSI/Nam
espaces/Types/Public/CingularDataModel.xsd" xmlns="http://csi.cingular.com/CSI/Namespaces/Types/Public/MessageHeader.xsd"><TrackingMessageHeader><cng:version>v68</cng:version><cng:originalVersion>v
68</cng:originalVersion><cng:messageId>46178</cng:messageId><cng:timeToLive>120000</cng:timeToLive><cng:conversationId>EDD~CNG-CSI~5bfa2f5f-103d-4056-b775-cb2028357a5c</cng:conversationId><cng:date
TimeStamp>2013-06-08T12:44:18.418Z</cng:dateTimeStamp><cng:uniqueTransactionId>ServiceGateway19121#q25csg1c1_4f771d65-41de-4c40-b4cc-0be179d3677c</cng:uniqueTransactionId></TrackingMessageHeader><S
ecurityMessageHeader><cng:userName>EDD</cng:userName><cng:userPassword>EDDtest</cng:userPassword></SecurityMessageHeader><SequenceMessageHeader><cng:sequenceNumber>1</cng:sequenceNumber><cng:totalInSequence>1</cng:totalInSequence></SequenceMessageHeader></MessageHeader></SOAP-ENV:Header> <SOAP-ENV:Body> <AddNoteResponse xmlns:cng="http://csi.cingular.com/CSI/Namespaces/Types/Public/CingularDataModel.xsd" xmlns="http://csi.cingular.com/CSI/Namespaces/Container/Public/AddNoteResponse.xsd"><Response><cng:code>0</cng:code><cng:description>Success</cng:description></Response></AddNoteResponse></SOAP-ENV:Body> </SOAP-ENV:Envelope>
11 Jun 2013 13:47:42,028 INFO doc [SOAP-ENV:Envelope: null]
11 Jun 2013 13:47:44,236 INFO elementName ://Envelope//Body//AddNoteResponse//Response//code
11 Jun 2013 13:47:44,236 INFO docNodes.getLength() :0
11 Jun 2013 13:47:44,243 INFO doc [SOAP-ENV:Envelope: null]
11 Jun 2013 13:47:44,254 INFO elementName ://Envelope//Body//AddNoteResponse//Response//description
11 Jun 2013 13:47:44,254 INFO docNodes.getLength() :0
But when I am trying the same code on my local system it is working fine:
Entering .convertStringToDoc()...
Exiting .convertStringToDoc()...
soapDocument [SOAP-ENV:Envelope: null]
9
xpath is not null
elementName :/Envelope/Body/AddNoteResponse/Response/code
docNodes length:1
value :0
docNodes length2:1
addNoteResponse.getCode
xpath is not null
elementName :/Envelope/Body/AddNoteResponse/Response/description
docNodes length:1
value :Success
docNodes length2:1
This is the response on which I am working with:
<SOAP-ENV:Envelope >
<SOAP-ENV:Header>
<MessageHeader >
<TrackingMessageHeader>
<cng:version>v68</cng:version>
<cng:originalVersion>v68</cng:originalVersion>
<cng:messageId>45266</cng:messageId>
<cng:timeToLive>120000</cng:timeToLive>
<cng:conversationId>xxx</cng:conversationId>
<cng:dateTimeStamp>2013-06-05T10:01:41.09Z</cng:dateTimeStamp>
<cng:uniqueTransactionId>xasas</cng:uniqueTransactionId>
</TrackingMessageHeader>
<SecurityMessageHeader>
<cng:userName>ass</cng:userName>
<cng:userPassword>asas</cng:userPassword>
</SecurityMessageHeader>
<SequenceMessageHeader>
<cng:sequenceNumber>1</cng:sequenceNumber>
<cng:totalInSequence>1</cng:totalInSequence>
</SequenceMessageHeader>
</MessageHeader>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<AddNoteResponse >
<Response>
<cng:code>0</cng:code>
<cng:description>Success</cng:description>
</Response>
</AddNoteResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Value I am interested in is:
<cng:code>0</cng:code>
<cng:description>Success</cng:description>
I have a problem in Java with DOM...
Here is the XML code :
<?xml version="1.0" encoding="UTF-8"?>
<bib>
<domain>
<title>Specifications</title>
<bib_ref>
<year>March 2000</year>
<title>MOF 1.3</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\MOF1_3.pdf</weblink>
</bib_ref>
<bib_ref>
<year>August 2002</year>
<title>IDLto Java LanguageMapping Specification</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\IDL2Java.pdf</weblink>
</bib_ref>
<bib_ref>
<year>1999</year>
<title>XML Metadata Interchange (XMI) Version 1.1</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\xmi-1.1.pdf</weblink>
</bib_ref>
<bib_ref>
<year>2002</year>
<title>XML Metadata Interchange (XMI) Version 2</title>
<author>"OMG</author>
<weblink>D:\SALIM\Docs\Specifications\XMI2.pdf</weblink>
</bib_ref>
<bib_ref>
<year>2002</year>
<title>XMI Version 1Production of XML Schema Specification</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\XMI1XSD.pdf</weblink>
</bib_ref>
<bib_ref>
<year>2002</year>
<title>EDOC</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\EDOC02-02-05.pdf</weblink>
</bib_ref>
</domain>
<domain>
<title>Theses</title>
<bib_ref>
<year>Octobre 2001</year>
<title>Echanges de Spécifications Hétérogènes et Réparties</title>
<author>Xavier Blanc</author>
<weblink>D:\SALIM\Docs\Theses\TheseXavier.pdf</weblink>
</bib_ref>
<bib_ref>
<year>Janvier 2001</year>
<title>Composition of Object-Oriented Software Design Models</title>
<author>Siobhan Clarke</author>
<weblink>D:\SALIM\Docs\Theses\SClarkeThesis.pdf</weblink>
</bib_ref>
......
......
After, in Java main function, I call the dispContent function which is just there:
public void dispContent (Node n)
{
String domainName = null;
// we are in an element node
if (n instanceof Element) {
Element e = ((Element) n);
// domain title
if (e.getTagName().equals("title") && e.getParentNode().getNodeName().equals("domain")) {
domainName = e.getTextContent();
DomaineTemplate(domainName);
}
else if (e.getTagName().equals("bib_ref")) {
NodeList ref = e.getChildNodes();
for (int i = 0; i < ref.getLength(); i++) {
Node temp = (Node) ref.item(i);
if (temp.getNodeType() == Node.ELEMENT_NODE) {
if (temp.getNodeType() == org.w3c.dom.Node.TEXT_NODE)
continue;
out.println(temp.getNodeName() + " : " + temp.getTextContent() + "\n");
}
}
}
else {
NodeList sub = n.getChildNodes();
for(int i=0; (i < sub.getLength()); i++)
dispContent(sub.item(i));
}
}
/*else if (n instanceof Document) {
NodeList fils = n.getChildNodes();
for(int i=0; (i < fils.getLength()); i++) {
dispContent(fils.item(i));
}
}*/
}
The "domaineTemplate" function just displays its parameter!
My problem happens when I browse the "bib_ref" tag in Java. For each "bib_ref" loop, it displays all the contents of all "bib_ref" tags... in one line! I want to display only one content (year, title, author and weblink tag) per "bib_ref".
Here is what it is displaying at the moment when I browse bib_ref :
Specifications
year : March 2000 title : MOF 1.3 author : OMG weblink : D:\SALIM\Docs\Specifications\MOF1_3.pdf year : August 2002 title : IDLto Java LanguageMapping Specification author : OMG weblink : D:\SALIM\Docs\Specifications\IDL2Java.pdf year : 1999 title : XML Metadata Interchange (XMI) Version 1.1 author : OMG weblink : D:\SALIM\Docs\Specifications\xmi-1.1.pdf year : 2002 title : XML Metadata Interchange (XMI) Version 2 author : OMG weblink : D:\SALIM\Docs\Specifications\XMI2.pdf year : 2002 title : XMI Version 1Production of XML Schema Specification author : OMG weblink : D:\SALIM\Docs\Specifications\XMI1XSD.pdf year : 2002 title : EDOC author : OMG weblink : D:\SALIM\Docs\Specifications\EDOC02-02-05.pdf
Theses
year : Octobre 2001 title : Echanges de Sp�cifications H�t�rog�nes et R�parties author : Xavier Blanc weblink : D:\SALIM\Docs\Theses\TheseXavier.pdf year : Janvier 2001 title : Composition of Object-Oriented Software Design Models author : Siobhan Clarke weblink : D:\SALIM\Docs\Theses\SClarkeThesis.pdf year : Juin 2002 title : Contribution � la repr�sentation de processu par des techniques de m�ta mod�lisation author : Erwan Breton weblink : D:\SALIM\Docs\Theses\ErwanBretonThesis.pdf year : Octobre 2000 title : Technique de Mod�lisation et de M�ta mod�lisation author : Richard Lemesle weblink : D:\SALIM\Docs\Theses\RichardLemesle.pdf year : Juillet 2002 title : Utilsation d'agents mobiles pour la construction des services distribu�s author : Siegfried Rouvrais weblink : D:\SALIM\Docs\Theses\theserouvrais.pdf
...
...
Can you help me ?
I'm just a beginner in xml with java and I'm searching some solution for about 3 hours... Thank's a lot!
I called dispContent(doc.getFirstChild()); where doc is the Document with your given xml file contents.
Assumptions: out.println() is System.out.println() and DomaineTemplate(domainName); adds a newline (based on your output provided)
I get the following print out in the console:
Specifications
year : March 2000
title : MOF 1.3
author : OMG
weblink : D:\SALIM\Docs\Specifications\MOF1_3.pdf
year : August 2002
title : IDLto Java LanguageMapping Specification
author : OMG
weblink : D:\SALIM\Docs\Specifications\IDL2Java.pdf
year : 1999
title : XML Metadata Interchange (XMI) Version 1.1
author : OMG
weblink : D:\SALIM\Docs\Specifications\xmi-1.1.pdf
year : 2002
title : XML Metadata Interchange (XMI) Version 2
author : "OMG
weblink : D:\SALIM\Docs\Specifications\XMI2.pdf
year : 2002
title : XMI Version 1Production of XML Schema Specification
author : OMG
weblink : D:\SALIM\Docs\Specifications\XMI1XSD.pdf
year : 2002
title : EDOC
author : OMG
weblink : D:\SALIM\Docs\Specifications\EDOC02-02-05.pdf
Theses
year : Octobre 2001
title : Echanges de Spécifications Hétérogènes et Réparties
author : Xavier Blanc
weblink : D:\SALIM\Docs\Theses\TheseXavier.pdf
year : Janvier 2001
title : Composition of Object-Oriented Software Design Models
author : Siobhan Clarke
weblink : D:\SALIM\Docs\Theses\SClarkeThesis.pdf
If you're having an issue with "\n" creating a new line, you can try using what the System uses:
public static final String NEW_LINE = System.getProperty("line.separator");
If you don't want the new lines between each line of the "bib_ref" node's children print outs, change:
else if (e.getTagName().equals("bib_ref")) {
NodeList ref = e.getChildNodes();
for (int i = 0; i < ref.getLength(); i++) {
Node temp = (Node) ref.item(i);
if (temp.getNodeType() == Node.ELEMENT_NODE) {
if (temp.getNodeType() == org.w3c.dom.Node.TEXT_NODE)
continue;
out.println(temp.getNodeName() + " : " + temp.getTextContent() + "\n");
}
}
}
to:
else if (e.getTagName().equals("bib_ref")) {
NodeList ref = e.getChildNodes();
for (int i = 0; i < ref.getLength(); i++) {
Node temp = (Node) ref.item(i);
if (temp.getNodeType() == Node.ELEMENT_NODE) {
if (temp.getNodeType() == org.w3c.dom.Node.TEXT_NODE)
continue;
// Removed "\n":
out.println(temp.getNodeName() + " : " + temp.getTextContent());
}
}
// Added out.println();
out.println();
}
Results:
Specifications
year : March 2000
title : MOF 1.3
author : OMG
weblink : D:\SALIM\Docs\Specifications\MOF1_3.pdf
year : August 2002
title : IDLto Java LanguageMapping Specification
author : OMG
weblink : D:\SALIM\Docs\Specifications\IDL2Java.pdf
year : 1999
title : XML Metadata Interchange (XMI) Version 1.1
author : OMG
weblink : D:\SALIM\Docs\Specifications\xmi-1.1.pdf
year : 2002
title : XML Metadata Interchange (XMI) Version 2
author : "OMG
weblink : D:\SALIM\Docs\Specifications\XMI2.pdf
year : 2002
title : XMI Version 1Production of XML Schema Specification
author : OMG
weblink : D:\SALIM\Docs\Specifications\XMI1XSD.pdf
year : 2002
title : EDOC
author : OMG
weblink : D:\SALIM\Docs\Specifications\EDOC02-02-05.pdf
Theses
year : Octobre 2001
title : Echanges de Spécifications Hétérogènes et Réparties
author : Xavier Blanc
weblink : D:\SALIM\Docs\Theses\TheseXavier.pdf
year : Janvier 2001
title : Composition of Object-Oriented Software Design Models
author : Siobhan Clarke
weblink : D:\SALIM\Docs\Theses\SClarkeThesis.pdf
Of course, now I see you have tagged your question with html and your code has nothing to do with html so far. So I asume out.println is some OutputStream for a Servlet and you're trying to Output html.
So the println linebreak, and the "\n" linebreaks are just available in the html sourcecode. The browser will skip this.
Change this line
out.println(temp.getNodeName() + " : " + temp.getTextContent() +
"\n");
to
out.println(temp.getNodeName() + " : " + temp.getTextContent() + "< br
/>");
and a servlet should output just fine with the linebreaks.