Hot to parse XML using JDOM?
<Case caseID="1808977179">
<attr name="create_time">2003-12-04 16:42:19.0</attr>
<attr name="name">1KEEJCE</attr>
<attr name="owner_id">2yawpgx5vhpus</attr>
<attr name="expected_closure">2003-12-04 16:42:19.0</attr>
<attr name="subject">test tech support case</attr>
</Case>
obviously my attribute name (which is also named as "name") is the same for all my five entries. How can I parse all of them?I can only parse the first entry.
this is the comp xml file:
<GetUserCasesResponse>
<Case caseID="1808977179">
<attr name="name">1KEEJCE</attr>
<attr name="create_time">2003-12-04 16:42:19.0</attr>
<attr name="owner_id">2yawpgx5vhpus</attr>
<attr name="expected_closure">2003-12-04 16:42:19.0</attr>
<attr name="subject">test tech support case</attr>
</Case>
<Case caseID="1326717944">
<attr name="name">2DC65T5</attr>
<attr name="create_time">2003-12-04 16:46:02.0</attr>
<attr name="owner_id">2yawpgx5vhpus</attr>
<attr name="expected_closure"></attr>
<attr name="subject">test tech support case</attr>
</Case>
<Case caseID="1489179651"><attr name="name">16ZUFEZ</attr>
<attr name="create_time">2003-12-04 16:48:15.0</attr>
<attr name="owner_id"></attr>
<attr name="expected_closure">2003-12-04 16:48:15.0</attr>
<attr name="subject">test tech support case</attr>
</Case>
<Case caseID="1145690438"><attr name="name">2Y3XDR7</attr>
<attr name="create_time">2003-12-04 16:56:17.0</attr>
<attr name="owner_id">2yawpgx5vhpus</attr>
<attr name="expected_closure">2003-12-04 16:56:17.0</attr>
<attr name="subject">testing</attr>
</Case>
<Case caseID="1145690438"><attr name="name">2Y3XDR7</attr>
<attr name="create_time">2003-12-04 16:56:17.0</attr>
<attr name="owner_id">2yawpgx5vhpus</attr>
<attr name="expected_closure">2003-12-04 16:56:17.0</attr>
<attr name="subject">testing</attr>
</Case>
</GetUserCasesResponse>
this is my code:
public static void readXML( )
try
SAXBuilder builder = new SAXBuilder( false );
Document doc = builder.build( new File(filenameConstant ) );
Element root = doc.getRootElement();
List listCase = root.getChildren("Case");
Iterator iterateCase = listCase.iterator();
while(iterateCase.hasNext())
Element attr = (Element) iterateCase.next();
System.out.println("" + attr.getChild("attr").getText() );
catch( Exception e)
e.printStackTrace();
This is my output:
1KEEJCE
2DC65T5
16ZUFEZ
2Y3XDR7
2Y3XDR7
Press any key to continue...
Obviously I can only get the first element (<attr name="name">1KEEJCE</attr>
) of each cases,how can I get the other four given that they have the same attribute name ( which is named "name" ).
Similar Messages
-
Hi all,
I am reposting it as I was told to format the code and send it again.
I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xml
<process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
<partnerLinks>
<partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
<partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
</partnerLinks>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
Java:
import java.io.*;
import java.util.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class sample1 {
public static void main(String[] args) throws Exception {
// create a XML parser and read the XML file
SAXBuilder oBuilder = new SAXBuilder();
Document oDoc = oBuilder.build(new File("**xml file location**"));
Element root = oDoc.getRootElement();
System.out.println(root.getName());
String tgtns= root.getAttributeValue("targetNamespace");
System.out.println("tgt ns "+ tgtns);
List list= root.getChildren("partnerLinks");
Iterator it1= list.iterator();
System.out.println("Iterator 1 - "+list.size());
while(it1.hasNext()){
Element partnerlinks = (Element)it1.next();
List list2= partnerlinks.getChildren("partnerLink");
System.out.println("iterator 2 - "+list2.size());
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Result:
Without Xmlns in xml file(Expected and correct output)
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
iterator 2 - 2
Result with xmlns:
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 0 //instead of 0 should return 1Hi all,
I am reposting it as I was told to format the code and send it again.
I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xml
<process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
<partnerLinks>
<partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
<partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
</partnerLinks>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
Java:
import java.io.*;
import java.util.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class sample1 {
public static void main(String[] args) throws Exception {
// create a XML parser and read the XML file
SAXBuilder oBuilder = new SAXBuilder();
Document oDoc = oBuilder.build(new File("**xml file location**"));
Element root = oDoc.getRootElement();
System.out.println(root.getName());
String tgtns= root.getAttributeValue("targetNamespace");
System.out.println("tgt ns "+ tgtns);
List list= root.getChildren("partnerLinks");
Iterator it1= list.iterator();
System.out.println("Iterator 1 - "+list.size());
while(it1.hasNext()){
Element partnerlinks = (Element)it1.next();
List list2= partnerlinks.getChildren("partnerLink");
System.out.println("iterator 2 - "+list2.size());
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Result:
Without Xmlns in xml file(Expected and correct output)
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
iterator 2 - 2
Result with xmlns:
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 0 //instead of 0 should return 1 -
Parsing xml using DOM parser in java
hi there!!!
i don have much idea about parsing xml.. i have an xml file which consists of details regarding indentation and spacing standards of C lang.. i need to read the file using DOM parser in java n store each of the attributes n elements in some data structure in java..
need help as soon as possible!!!DOM is the easiest way to parse XML document, google for JDOM example it is very easy to implement.
you need to know what is attribute, what is text content and what is Value in XML then easily you can parse your document with dom (watch for space[text#] in your XML document when you parse it).
you get root node then nodelist of childs for root then go further inside, it is easy believe me. -
How do i parse this, using JDOM?!
This xml is in the form of a String, can someone tell me how to use JDOM to parse this, i've actually made a start:
SAXBuilder builder = new SAXBuilder();
Reader r = new StringReader(str1);
Document doc = builder.build(r);
<StockQuotes>
<Stock>
<Symbol>IBM</Symbol>
<Last>111.32</Last>
<Date>8/1/2007</Date>
<Change>+0.67</Change>
<Open>110.39</Open>
<High>111.95</High>
<Low>110.06</Low>
</Stock>
</StockQuotes>
and then im kinda lost... please help! really need it!
cheers,
Shivek Sachdevhey,
thanks a lot for the reply.
i get the idea now, to be able to trace to the childrens
but it would be really helpful if u can give me a more complete version of the code, im really new to this stuff.
i did wat u told:
List stock = root.getChildren();
//now im at the 2nd level
how do i get to <Symbol> so that i can print out the value of that tag.
cheers,
Shivek Sachdev -
Importing/Parsing XML using SQL and/or PL/SQL
What is the recomended way of importing/parsing XML data using SQL and/or PL/SQL?
I have an XSD that defines the structure of the file, and an XML file that has the content in the appropriate structure. I have parsed (checked) the structure of the XML file using JDOM in my java application, and then passed it to a function in a package on the database as a CLOB.
What I need to do is parse the contents of the XML file that is passed into the function and extract the values of each XML element so that I can then do some appropriate validation before inserting and committing the data to the database (hence completing the import function).
A DBA colleague of mine has been experimenting with various ways of acheiving this, but has encountered a number of problems along the way, one of which being that he thinks that it is not possible to parse XML elements that are nested more than four levels deep - is this the case?
The structure of the XSD/XML that the database function needs to manipulate and import data from is very complex (and recursive by it's nature).
I would appreciate any suggestions as to how I can achieve the above in the most efficient manner.
Thanks in advance for your help
DavidThis is the forum for the SQLDeveloper tool. You will get better answers in the SQL and PL/SQL forum, and especially the XML DB forum.
Oracle has comprehensive and varied support for XML, including a PL/SQL parser. -
Problem in parsing XML using DOM Parser.
Hi,
I am parsing an XML using DOM Parser.
When i try to get attributes of a node, i dont get in the order it is written. For Eg. This the node:
<Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa">
When i try to print the attribute values i should get in the order:
News, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, 202, COGN-4MNMT3, aaaa
BUT I AM GETTING IN THE ORDER:
News, 202, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, aaaa, COGN-4MNMT3
Is there any way to sort this problem out?
Thanks and Regards,
AshokHi Guys,
Thanks a lot for your replies.
But i want to keep all the values as attributes only.
the XML file is as shown below:
<Menu>
<Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa" children="3">
<Level1 label="ING News" link="" level="1" uid="COGN-4MNN89" parentid="COGN-4MNMT3" children="3" >
<Level2 label="All ING News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="2" uid="INGD-4MVTK2" parentid="COGN-4MNN89" children="0">
</Level2>
</Level1>
</Level0>
The code i was using to get attributes is:
String strElementName = new String(node.getNodeName());
// System.out.println("strElementName:"+node.getNodeName());
NamedNodeMap attrs = node.getAttributes();
if (attrs != null) {
int iLength = attrs.getLength();
for (int i = 0; i < iLength; i++) {
String strAttributes = (String) attrs.item(i).getNodeName();
String strValues = (String) attrs.item(i).getNodeValue();
Also is it not possible to Enforce the order using some Schema/DTD in this case?
TIA
Ashok -
How to parse XML using SAX Parser sequencially
I have a requirement to parse XML file sequencially. But I need to stop the parsing in-between for doing some processing.
Let me explain with example
I have a file with following structure.
<InputFile>
<Invoice>
<InvoiceNo = "Inv1"/>
<InvoiceDt = "12012002"/>
</Invoice>
<Invoice>
<InvoiceNo = "Inv2"/>
<InvoiceDt = "12012002"/>
</Invoice>
<Invoice>
<InvoiceNo = "Inv3"/>
<InvoiceDt = "12012002"/>
</Invoice>
For each Invoice node I need to process some activites. So I need to write a method which will open the XML file and parse and returns me a complete element from <invoice> to </Invoice> sequencially.
Please let me know whther some body has solution for this.
Manoj.If you're using a SAX parser then you can implement your code in the startElement(), endElement(), and characters() methods... have a look at the tutorial here:
http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/index.html -
Hi All,
I am getting error while loading XML in <fx:XML> tag.
Error:
TypeError: Error #1090: XML parser failure: element is malformed.
MXML Code:
<fx:Declarations>
<fx:XML id="xmlSource2" source="sample.xml"/>
</fx:Declarations>
Sample XML Used: (sample.xml)
<?xml version="1.0" encoding="UTF-8"?>
<File>
<Chemical id="000035676" displayFormula="C39-H45-N2-O6"
displayName="Dimethyltubocurarine">
<NameList>
<NameOfSubstance>
Dimethyltubocurarine
<SourceList>
<Source>MESH</Source>
</SourceList>
</NameOfSubstance>
<SystematicName>
Tubocuraranium, 6,6',7',12'-tetramethoxy-2,2',2'-trimethyl-
<SourceList>
<Source>NLM</Source>
</SourceList>
</SystematicName>
<Synonyms>
Dimethyltubocurarine
<SourceList>
<Source>NLM</Source>
</SourceList>
</Synonyms>
<Synonyms>
Dimethyltubocurarinium
<SourceList>
<Source>NLM</Source>
</SourceList>
</Synonyms>
<Synonyms>
Methyltubocurarinum
<SourceList>
<Source>NLM</Source>
</SourceList>
</Synonyms>
</NameList>
<NumberList>
<CASRegistryNumber>
35-67-6
<SourceList></SourceList>
</CASRegistryNumber>
<RelatedRegistryNumber>
518-26-3 (iodide.hydriodide)
<SourceList>
<Source>MESH</Source>
</SourceList>
</RelatedRegistryNumber>
</NumberList>
<ClassificationList>
<ClassificationCode>
Neuromuscular nondepolarizing agents
<SourceList>
<Source>MESH</Source>
</SourceList>
</ClassificationCode>
</ClassificationList>
<FormulaList>
<MolecularFormula>
C39-H45-N2-O6
<SourceList>
<Source>NLM</Source>
</SourceList>
</MolecularFormula>
</FormulaList>
<FormulaFragmentList></FormulaFragmentList>
<NoteList></NoteList>
<LocatorList>
<FileLocator
url="http://cnetdb.nci.nih.gov/cgi-bin/srchcgi.exe?DBID=****3&SFMT=****_basic%2F10%2F0%2F0&TYPE=search&SRCHFORM=passthru%3D%Asrchform%3ASRCH%3A&FIELD_001=[CAS]35-67-6&GoButton=Search&FIELD_001_CTL=EXPR&FIELD_908=&FIELD908_CTL=HASABSTRACT&FIELD_903=&FIELD_903_CTL=YEARFORE&DOCPAGE=10">CANCERLIT</FileLocator>
<FileLocator
url="http://toxnet.nlm.nih.gov/cgi-bin/sis/search/r?dbs+toxline:@and+@term+@rn+35-67-6+@term+@org+DART">DART/ETIC</FileLocator>
<FileLocator
url="http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=search&db=PubMed&term=35-67-6[ECNO]+OR+"~"[MH]">MEDLINE</FileLocator>
<FileLocator
url="http://www.nlm.nih.gov/cgi/mesh/2K/MB_cgi?term=35-67-6&rn=1">MESH</FileLocator>
<FileLocator
url="http://toxnet.nlm.nih.gov/cgi-bin/sis/search/r?dbs+toxline:@term+@rn+35-67-6+@OR+@mh+""">TOXLINE</FileLocator>
</LocatorList>
</Chemical>
</File>
Also, when I am using HttpService to load same XML I am getting no such error!!
<s:HTTPService id="employeeService"
url="sample.xml"
result="employeeService_resultHandler(event)"
fault="employeeService_faultHandler(event)"/>
Please help!!
Thanks.
AbhinavI think url in XML is creating problem here.
<FileLocator
url="http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=search&db=PubMed&term=23-95-0[ECNO]+OR+"~"[MH]">MEDLINE</FileLocator>
Is there any way to parse this XML using <fx:XML/> ??
Thanks. -
hi
how to read and edit xml file using jdom, i tried using
javax.xml.transform.*; // JAXP
javax.xml.transform.dom.DOMSource; //
i can read xml file . but iam not able to edit the xml file.
how to achive this1. Select nodes to be modified with the JDom XPath class selectSingleNode and selectNodes methods.
SAXBuilder saxBuilder=new SAXBuilder("org.apache.xerces.parsers.SAXParser");
org.jdom.Document jdomDocument=saxBuilder.build(new File("c:/input.xml"));
org.jdom.Element node= (org.jdom.Element)(XPath.selectSingleNode(jdomDocument,"/root/node"));
2. Modify the node values with the Element class setter methods.
3. Output document with the XMLOutputer class. -
Parsing XML using SDO API.
Hi
I am looking to see if JDeveloper comes with necesssary SDO APIs to help
a developer parse XML. I am looking at this as a replacement for JAXB.
I have access to JDev 11g and 10g.
If it is possible can you please tell me
1) What are the libraries to include?
2) Any tutorials available.
Thanks
KartikHello Kartik,
Oracle TopLink will include an SDO 2.1 implementation as part of the AS 11R1 release. You can take a look at Technical Preview 2 here:
http://www.oracle.com/technology/products/ias/toplink/preview/index.html
There isn't much in the way of SDO documentation yet, but I can provide you with some samples if you wish.
First though, you mention that you are looking for a replacement for JAXB. I have represented Oracle on both the JAXB 2.0 and SDO 2.1/3.0 specifications so if you care to provide details on what you're building, maybe I can offer an opinion. If you don't wish to post to the list, you can email me at [email protected]
Oracles JAXB and SDO implementations are both build on top of TopLink's object-to-XML mapping technology. This may also be an appropriate technology choice for you.
For more information on TopLink OXM see:
http://www.oracle.com/technology/products/ias/toplink/oxm/index.html
-Blaise -
Parsing a XML using Jdom --- Problem pls help
Hi all,
I am reposting it as I was told to format the code and send it again.
I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xml
<process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
<partnerLinks>
<partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
<partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
</partnerLinks>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
Java:
import java.io.*;
import java.util.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class sample1 {
public static void main(String[] args) throws Exception {
// create a XML parser and read the XML file
SAXBuilder oBuilder = new SAXBuilder();
Document oDoc = oBuilder.build(new File("**xml file location**"));
Element root = oDoc.getRootElement();
System.out.println(root.getName());
String tgtns= root.getAttributeValue("targetNamespace");
System.out.println("tgt ns "+ tgtns);
List list= root.getChildren("partnerLinks");
Iterator it1= list.iterator();
System.out.println("Iterator 1 - "+list.size());
while(it1.hasNext()){
Element partnerlinks = (Element)it1.next();
List list2= partnerlinks.getChildren("partnerLink");
System.out.println("iterator 2 - "+list2.size());
}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Result:
Without Xmlns in xml file(Expected and correct output)
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
iterator 2 - 2
Result with xmlns:
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 0 //instead of 0 should return 1One suggestion to try:
Change your code to the following
Element root = oDoc.getRootElement();
System.out.println(root.getName());
String tgtns= root.getAttributeValue("targetNamespace");
System.out.println("tgt ns "+ tgtns);
Namespace ns = Namespace.getNamespace(
"http://schemas.xmlsoap.org/ws/2003/03/business-process/" );
List list= root.getChildren("partnerLinks", ns );
Iterator it1= list.iterator();
System.out.println("Iterator 1 - "+list.size());The JavaDoc says for the one-arg getChildren()
If this target element has no nested elements with the given name outside a namespace, an empty List is returned.
Your elements have a namespace (the default one) so it should be worth a try.
Dave Patterson -
Problem parsing a xml using Jdom
Hi all,
I am reposting it as I was told to format the code and send it again.
I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xml
<process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
<partnerLinks>
<partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
<partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
</partnerLinks>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
Java:
import java.io.*;
import java.util.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class sample1 {
public static void main(String[] args) throws Exception {
// create a XML parser and read the XML file
SAXBuilder oBuilder = new SAXBuilder();
Document oDoc = oBuilder.build(new File("**xml file location**"));
Element root = oDoc.getRootElement();
System.out.println(root.getName());
String tgtns= root.getAttributeValue("targetNamespace");
System.out.println("tgt ns "+ tgtns);
List list= root.getChildren("partnerLinks");
Iterator it1= list.iterator();
System.out.println("Iterator 1 - "+list.size());
while(it1.hasNext()){
Element partnerlinks = (Element)it1.next();
List list2= partnerlinks.getChildren("partnerLink");
System.out.println("iterator 2 - "+list2.size());
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Result:
Without Xmlns in xml file(Expected and correct output)
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
iterator 2 - 2
Result with xmlns:
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 0 //instead of 0 should return 1One suggestion to try:
Change your code to the following
Element root = oDoc.getRootElement();
System.out.println(root.getName());
String tgtns= root.getAttributeValue("targetNamespace");
System.out.println("tgt ns "+ tgtns);
Namespace ns = Namespace.getNamespace(
"http://schemas.xmlsoap.org/ws/2003/03/business-process/" );
List list= root.getChildren("partnerLinks", ns );
Iterator it1= list.iterator();
System.out.println("Iterator 1 - "+list.size());The JavaDoc says for the one-arg getChildren()
If this target element has no nested elements with the given name outside a namespace, an empty List is returned.
Your elements have a namespace (the default one) so it should be worth a try.
Dave Patterson -
Hi,
I am trying to extract an xml document from a URL which, when i use "httpuri.getContentType()", it is returning "text/html" instead of "text/xml". Therefore, i could not use getXML() method to parse it into xmltype for processing. What other way can i parse it into an xmltype? Thanks for the help
Regards
vivianAre you sure that it is actually accessing the XML Document correctly. Can you check what httpuri.getclob() returns. If this is returning the document then you can do xmltype(httpuri.getClob()). If this is not returning the docuemnt then you probably need to configure http proxies correctly.
-
How to parse xml using DocumentBuilder ?
I am trying to parse this xml snippet:
<root>
<data a="0.0" b="1.0"/>
<data a="0.1" b="2.0"/>
<data a="0.2" b="3.0"/>
<data a="0.3" b="4.0"/>
<data a="0.4" b="5.0"/>
<data a="0.5" b="6.0"/>
</root>
using the following:
String test = getDummyXmlSnippet()
StringReader sr = new StringReader(test);
input = new InputSource(sr);
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(input);
NodeList nodes = document.getChildNodes();
// this only prints 1
System.out.println(nodes.getLength());
Node nn = nodes.item(0);
// this prints this first root node name (root)
System.out.println(nn.getNodeName());
// Cannot get the remaning nodes....!
NodeList nnt = nn.getChildNodes();
Node n0 = nnt.item(0);
System.out.println(n0.getNodeValue()); // just prints #text
System.out.println(n0.getNodeName()); // just prints #text
// THis prints 13
System.out.println(nn.getChildNodes().getLength());
// this will only iterate once!
NodeList children = document.getChildNodes();
for (int i=0;i<children.getLength();i++) {
Node node = children.item(i);
if (node.getNodeType()==Node.ELEMENT_NODE) {
System.out.println("bob = " + node.getNodeName());
} catch(Exception e){
e.printStackTrace();
}I can only get the first root node printed. How do I get the child (data nodes) elements out?What do you mean by the "first" root node? An XML document only has one root node, and your XML document is no exception.
As for the 13 child nodes of the root, you could have written a program which iterated over them and displayed them. That would have clarified your understanding of the document. But instead you wrote a program which just displayed the first of them, then iterated over the children of the document (which has the root as its only child) instead of iterating over the children of the root element.
You wouldn't be the first person to not realize that whitespace text nodes are nodes just like all the others. Or that the document and the root node are different things. -
hi
i am trying to parse a document and change a specific text value within an element althouh when i run the program it changes the nodes text however when i check the xml file it doesnt show the changes it remains the same the code that i am using is as follow iwould be greatful if any one culd help:
// ReplaceText.java
// Reads intro.xml and replaces a text node.
// Java core packages
import java.io.*;
// Java extension packages
import javax.xml.parsers.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
// third-party libraries
import org.xml.sax.*;
import org.w3c.dom.*;
public class ReplaceText {
private Document document;
public ReplaceText()
// parse document, find/replace element, output result
try {
// obtain default parser
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// set parser as validating
factory.setValidating( true );
// obtain object that builds Documents
DocumentBuilder builder = factory.newDocumentBuilder();
// set error handler for validation errors
builder.setErrorHandler( new MyErrorHandler() );
System.err.println( "reading" );
// obtain document object from XML document
File f = new File("D:/Documents and Settings/Administrator/Desktop/xml adv java bk/appC/intro.xml");
System.err.println( "reading" );
document = builder.parse(f);
//document = builder.parse( new File( "intro.xml" ) );
System.err.println( "reading document" );
// retrieve the root node
Node root = document.getDocumentElement();
if ( root.getNodeType() == Node.ELEMENT_NODE ) {
Element myMessageNode = ( Element ) root;
NodeList messageNodes =
myMessageNode.getElementsByTagName( "message5" );
if ( messageNodes.getLength() != 0 ) {
Node message = messageNodes.item( 0 );
System.out.println("iiiii");
// create text node
Text newText = document.createTextNode(
"New Changed Message!!" );
// get old text node
Text oldText =
( Text ) message.getChildNodes().item( 0 );
// replace text
//message.removeChild(oldText);
message.replaceChild( newText, oldText );
// output Document object
// create DOMSource for source XML document
Source xmlSource = new DOMSource( document );
// create StreamResult for transformation result
Result result = new StreamResult( System.out );
// create TransformerFactory
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
// create Transformer for transformation
Transformer transformer =
transformerFactory.newTransformer();
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.setOutputProperty( OutputKeys.STANDALONE, "yes" );
// transform and deliver content to client
transformer.transform( xmlSource, result );
// handle exception creating DocumentBuilder
catch ( ParserConfigurationException parserException ) {
parserException.printStackTrace();
// handle exception parsing Document
catch ( SAXException saxException ) {
saxException.printStackTrace();
// handle exception reading/writing data
catch ( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
// handle exception creating TransformerFactory
catch (
TransformerFactoryConfigurationError factoryError ) {
System.err.println( "Error while creating " +
"TransformerFactory" );
factoryError.printStackTrace();
// handle exception transforming document
catch ( TransformerException transformerError ) {
System.err.println( "Error transforming document" );
transformerError.printStackTrace();
public static void main( String args[] )
ReplaceText replace = new ReplaceText();
}the xml file that i am using is as follows:
<?xml version = "1.0"?>
<!-- Fig. 28.10 : intro.xml -->
<!-- Simple introduction to XML markup -->
<!DOCTYPE myMessage [
<!ELEMENT myMessage (message, message5)>
<!ELEMENT message (#PCDATA)>
<!ELEMENT message5 (#PCDATA)>
]>
<myMessage>
<message>welcome to the xml shhhhhushu</message>
<message5>welcome to the xml shhhhhushu</message5>
</myMessage>i would be greatful if some one could please help.....See if the Text 'oldText' actually has any text within it. Sometimes in DOM parsing, you will get something like:
Element
Text (blank)
Text (actual)
Text (blank)Whereas you would expect to receive:
Element
Text (actual)See if that is the case. If yes, modify your logic to iterate through the child text nodes until one with actual text inside of it (getNodeValue()) is found.
- Saish
Maybe you are looking for
-
Is there any way to generate table of contents in adobe for a report output
Hi All, I need to display the output of a report in an PDF and layout needs to be developed in Adobe Print Forms. I want to know if there is a way to generate a table of contents for the output in adobe form on a particular page. Thanks...
-
Setting file name for a downloaded file
I've set up a file download using code I've gleaned from jsf forums. However, the file name is not being set correctly. When the user downloads File.doc, it shows up as downloadPage.jsf. Am I setting the header correctly? public class VendorInfoBean
-
Java.lang.UnsatisfiedLinkError: InvocationTargetException
Hi, I use Oci driver for use an Oracle 10g database, and so, a oracle client 10.0.2. I'm on Solaris 8 Sparc 64bits. And I have this error message : java.lang.UnsatisfiedLinkError: /export/home0/product/oracle/10.2.0/client_1/lib/libocijdbc10.so: ld.s
-
What's best for allowing document download?
Hi All, Quick question really. I'm looking to create a simple HTML page which is to provide documents and photos to be downloaded. Essentially there will be several pdfs and high res images for people to download and I was wondering what the best way
-
Editing RAW (*ORF) in Photoshop10
Hi i have photoshop elements 10 and cant edit RAW files in the ORF format, although my camera (EPL5 Olympus) is in the list. I tried to download and install a recent RAW plugin, but this didn't help. Tips are very welcome!