JDOM - Accessing XML Elements
I have an XML file which have multiple element with same tag but different attribute. If I want to access a specific element with the require attribute, at the moment, I access every element and check it's attribute. Is there a way/method to get an element with the required attribute directly using JDOM
ehm..
Can you show how I have to do to get an element from a Xml file using Jdom and Xpath?
my xml file is like this:
<catalog>
<param1>
<name> XXX </name>
<price> YYY </price>
</param1>
<param2>
<name> EEE </name>
<price> RRR </price>
</param2>
<param3>
<name> TTT </name>
<price> GGG </price>
</param3>
</catalog> tnx & bye
Similar Messages
-
How to access XML elements by name in Extendscript??
I'm almost done the script that I've been working on, but something has been nagging me since I started. When I did start, I looked at the JS Tools Guide CS5 that comes with the extendscript ide to check how to access XML elements, children, attributes etc. It says this:
The XML object represents an XML element node in an XML tree. The topmost XML object for an XML file
represents the root node. It acts as a list, which contains additional XML objects for each element. These in
turn contain XML objects for their own member elements, and so on.
The child elements of an element tree are available as properties of the XML object for the parent. The
name of the property corresponds to the name of the element. Each property contains an array of XML
objects, each of which represents one element of the named type.
So basically it converts the XML into JSON. And you can access the properties like so:
<book category="COOKING">
<title lang="en">The Boston Cooking-School Cookbook</title>
<author>Fannie Merrit Farmer</author>
<year>1896</year>
<price>49.99</price>
</book>
The Javascript statement bookstoreXML.book; returns the entire list of books.
The statement bookstoreXML.book[0]; returns the XML object for the first book.
The statement bookstoreXML.book[0].author; returns all authors of the first book.
A couple pages down it talks about Retrieving contained elements using children(), elements(), descendants().
So now I look through the XML Object properties and I see that I can use:
xmlObj.child (which) which A String, the element name, or a Number, a 0-based index into this node’s child array.
or
xmlObj.descendants ([name])
name Optional. A String, the element name to match. If not provided, matches all
elements.
or
xmlObj.elements (name);
name Optional. A String, the element name to match. If not provided, matches all
elements.
This is an excerpt of an XML I was working with:
<ROW xmlns="http://www.filemaker.com/fmpdsoresult"
MODID="16"
RECORDID="11128">
<Sign_Type>251.dr</Sign_Type>
<fm:Location xmlns:fm="http://www.filemaker.com/fmpdsoresult" xmlns="">5-5024</fm:Location>
<Line1>Zone
Floor
3
Patient Rooms
R532 - R436 even
Patient Rooms
R522 - R446 even
Xavier Elevators
Zone
Patient Rooms
R537 - 5757 odd
Main Elevators
Zone</Line1>
</ROW>
Extendscript will not give me an anything when I try to access elements by name. Instead I have to access by index, which works, but I'd rather search for names!
Actually the console log returns: <![CDATA[]]>
What am I doing wrong!?First, those E4X XML objects are definitely no JSON (plain data) - they have a multitude of methods, even for tasks that would easily be implemented as property (e.g. the length() function), and they also bind xml element and attribute names onto the objects, allowing to target a multitude of XML nodes with a single statement. Or did you mean your script with that "it"?
Anyway, as you found out the ExtendScript XML object handles namespaces mostly by hiding them from you.
You could play around with global namespace settings, see the JavaScript tools guide.
You could also explicitly specify a namespace. This works for me:
$.writeln(myXML["fm:Location"]);
For simple use I had most success with a brute force approach that just strips the namespaces.
function removeAllNamespace(xml)
var ns =new Namespace();
var d=xml.descendants();
for (var i=0;i<d.length();i++)
d[i].setNamespace(ns); -
Re: Jdom access mulitple elements
Look into xpath, it's a very powerful and simple querying tool for xml. JDom supports it as well. Here's a good tutorial: http://www.zvon.org/xxl/XPathTutorial/General/examples.html
What you want is "//course" which will match all "course" elements anywhere in the document. Check out example 2 in that tutorial for an example.ehm..
Can you show how I have to do to get an element from a Xml file using Jdom and Xpath?
my xml file is like this:
<catalog>
<param1>
<name> XXX </name>
<price> YYY </price>
</param1>
<param2>
<name> EEE </name>
<price> RRR </price>
</param2>
<param3>
<name> TTT </name>
<price> GGG </price>
</param3>
</catalog> tnx & bye -
How to insert Text physically to xml in xml Element
hello friends,
I am newb of jDom. i am trying to change xml "Element's"--->"Text". My xml is as follows .....
<?xml version ="1.0">
<Elements>
<code>
<data>EE550</data>
</code>
</Elements> I am trying to replace that "<data>" by <data>AA550</data>
my code is as below
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(new File("src/xml/M90EE.xml"));
Element element = doc.getRootElement();
List children = element.getChildren();
String key = (element.getChild("text").getChild("mkey").setText("AA550").getTextTrim()); System.out.println("mkey :"+key);
output:
mkey :AA550 but is it possible to change in the xml file phisically.
thanQ
Ajayhello Reegz,
ThanQ so much for perfect solution....
when i do like that it is actually adding text to the existing Element Text.. so i wrote as follows....
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(new File("src/xml/M90EE.xml"));
*String skey = (element.getChild("text").getChild("mkey").removeContent().toString());* //--------->step 1
*String skey1 = (element.getChild("text").getChild("mkey").addContent("ISO9001").toString());* //-------->step 2
String rdmkey = (element.getChild("text").getChild("mkey").getTextTrim());
XMLOutputter serializer = new XMLOutputter();
String str = serializer.outputString(doc);
FileWriter fr = new FileWriter("src/xml/M90EE.xml");
fr.write(str);
fr.flush();
fr.close();Is there any other way to replace text in step1 and step2 other than above or will it be enough for multiuser programming. Because this application will be accessed by so many number of user's what do u sujjest.
thanQ ...
Han. -
How can we get the reference of XML element on frame as soon as frame is created in Document?
Hi,
When ever we copy any text/table cells from any frame, and paste it directly on page, A new Frame is created and the pasted text is placed inside that frame.
Now to capture this frame creation, We have two possible solutions:
1) Attach Observer on Document 'kDocBoss' on IID_IHIERARCHY_DOCUMENT and it will notify on frame creation in update function.
2) Notification event on new story creation.
Now, I need to perform some changes in the newly created table, for example:
a) Need to delete XML tags from newly created frame
b) Need to perform action on table cells if any in the created frame.
But the problem is, when the event comes, I can access basic properties of frame like it's name, type etc, but it does not give me the
XML element on frame or tables in frame until the event is com pleat.
I know it's quite a specif requirement, but I guess many of you might have faced these kind of challenges, while processing the event.
Does any one has any idea how I can get the reference of XML element on frame as soon as it is created?Hi Kapoor,
please give also others a chance, and excuse that I get up late on vacation ;-)
Anyway, I'd keep the story creation responder to recognize the copy, then combine it with an observer on the backing xml story to catch the associated XML element which is created there. Something like below:
UIDRef xmlStoryRef = Utils<IXMLUtils>()->GetBackingStore(doc);
InterfacePtr<ISubject> subject ( xmlStoryRef,IID_ISUBJECT );
subject->AttachObserver(observer,IID_IIDXMLELEMENT,observer->GetAttachIID()); -
How to access XML attributes with JSTL
Hello,
I'm using the XML functions of JSTL. I'm trying to parse the following RSS feed.
http://weather.yahooapis.com/forecastrss?p=USNY0996
I can get it parsed and access the elements via JSTL, but is it possible to access the attributes of some of the elements?
For example, how can I get the city attribute out of
<yweather:location city="New York" region="NY" country="US" />Hello,
I'm using the XML functions of JSTL. I'm trying to parse the following RSS feed.
http://weather.yahooapis.com/forecastrss?p=USNY0996
I can get it parsed and access the elements via JSTL, but is it possible to access the attributes of some of the elements?
For example, how can I get the city attribute out of
<yweather:location city="New York" region="NY" country="US" /> -
Problem changing XML element in Adapter Module
Hey!
I am developing an adapter module to transform a coded password back to clear text. I have access to the XML element where the password is and I get to transform it, but I have 2 problems as also stated in the code:
1) I cannot set the new value back to the node. I try with
firstNode.getFirstChild().setNodeValue(decodedPwd);
but this does not seem to work. How can I achieve this?
2) Between the first issue and the code
msg.setDocument(xmlpayload);
I am not sure how to get my new values for the node back in the XMLPayload. How can I achieve this?
Here is the code:
msg = (Message) inputModuleData.getPrincipalData();
XMLPayload xmlpayload = msg.getDocument();
factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse((InputStream)xmlpayload.getInputStream());
password = (Element)document.getElementsByTagName("ns1:passord").item(0);
firstNode = password.getFirstChild();
pwd = firstNode.getNodeValue();
if(pwd != null){
decodedPwd = Decoder.decodeString(pwd);
// THIS FAILS!
firstNode.getFirstChild().setNodeValue(decodedPwd);
//HOW TO SET NEW NODE VALUE TO XMLPAYLOAD HERE?
msg.setDocument(xmlpayload);
inputModuleData.setPrincipalData(msg);
return inputModuleData;
Help is much appreciated!
Thanks!
regards OleHey!
The problem was solved. The code snipped I found was:
DOMSource DOMSource = new DOMSource(document);
ByteArrayOutputStream myBytes = new ByteArrayOutputStream();
Result dest = new StreamResult(myBytes);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.transform(DOMSource, dest);
byte[] docContent = myBytes.toByteArray();
xmlpayload.setContent(docContent);
msg.getDocument().setContent(xmlpayload.getContent());
Ole
Edited by: Ole Mugaas on Mar 27, 2008 8:43 PM -
Multi-level nested tables for repeatable XML Elements
Hi there,
Suppose we have a XML Schema „ASchema“ like this (XMLDB schema annotations are left out for simplicity):
<xs:schema xmlns:xs=" .... " />
<xs:element name=“A“>
<xs:complexType>
<xs:sequence>
<xs:element name=“B“ maxOccurs=“unbounded“/>
<xs:complexType>
<xs:sequence>
<xs:element name = “C“ maxOccurs=“unbounded“/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
After registering this schema in Oracle, I can define a table like this:
CREATE TABLE ATable
id NUMBER,
doc XMLTYPE
XMLTYPE COLUMN doc
XMLSCHEMA “ASchema“ ELEMENT “A“
VARARRAY doc.“XMLDATA“.“B“ STORE AS TABLE “BTable“
((PRIMARY KEY (NESTED_TABLE_ID, SYS_NC_ARRAY_INDEX$)) ORGANIZATION INDEX)
This creates a nested table "BTable" within the table "ATable". So far so good, I can use this nested table to gain faster access on every possible subelement of Element B when I set an appropriate index.
I now want to create another nested table for element “C“ like this:
DROP TABLE ATable;
CREATE TABLE ATable
id NUMBER,
doc XMLTYPE
XMLTYPE COLUMN doc
XMLSCHEMA “ASchema“ ELEMENT “A“
VARARRAY doc.“XMLDATA“.“B“ STORE AS TABLE “BTable“
((PRIMARY KEY (NESTED_TABLE_ID, SYS_NC_ARRAY_INDEX$)) ORGANIZATION INDEX)
VARARRAY doc.“XMLDATA“.“B“.“C“ STORE AS TABLE “CTable“
((PRIMARY KEY (NESTED_TABLE_ID, SYS_NC_ARRAY_INDEX$)) ORGANIZATION INDEX)
But this statement fails with the error message something like „ ... no such attribute ... „
And here's my question: is it possible to create nested tables for repeatable XML Elements that are subelements of other repeatable XML Elements ? And if so, how can I do it ?
Thank you very much in advance
JanFound a (partial) solution myself:
If you add the attribute xdb:storeVarrayAsTable="true" to the root element of the XML schema, Oracle XMLDB generates nested tables for all repeatable XML Elements while registering the XML schema.
Unfortunately, the names of these nested tables are system-generated, hence it's a bit uncomfortable to set indices on them. You can find out the names of these nested tables as follows:
select table_name, parent_table_name, parent_table_column from user_nested_tables;
Further information on that subject is supplied in the following thread:
Re: default tables for elements with maxoccurs > 1
It would be nice if there was a way to name the generated nested tables via appropriate XMLDB schema annotations.
regards
Jan -
XML element,if not including any attributes and/or child elements then
XML element in SQLX,if not including any attributes and/or child elements then the tag should not appear, how to achive this?
ex:Consider for <enumeration> tag where it is having some value.
<attribute>
<name>Ethernet Access</name>
<enumeration>
<StringValue>Bandwidth</StringValue>
</enumeration>
</attribute>
When <enumeration> tag is not have any Value in this, then output should be as follows.
<attribute>
<name>Ethernet Access</name>
</attribute>
But what i am getting is
<attribute>
<name>Ethernet Access</name>
</enumeration>
</attribute>
Please suggest me the solution for this.
I tried , but when xmlelement() is not having data it will display empty tag ie </enumeration>, If xmlforest() are null it wont show tag, But i have to use xmlelement only. how can that be achived using xmlelement .Use a SQL case - when - else end construct to only execute the xmlelement if data is present. The SQL/XML standard is very clear, xmlElement will generate an empty element if no data is present. xmlforest will not.
-
Pass an XML element path in as a parameter of a class.
Hey all,
I am creating a class to handle some audio in an app I am building. This class will need to accept the XML element path as a passed parameter and or a getter.
examples of some XML elements I would like to pass to the the audio handler class to access them.
Dialog.introScreen.text
or
Dialog.secondScreen.main.text
ect.
I pretty sure this is not a string data type and thus cannot be passed as a string (I could be wrong though), if not, what data type would I pass it as?
Thanks.you're welcome.
(and, you'll find out soon enough what type that is. if you try and cast that as an XMLList item - or anything else that can't be coerced into that type, flash will tell you it can't convert a Sprite or whatever into an XMLList object.) -
How to create XML element with out creating a document
I ve been looking for hours for a method to create an XML element without the need for the Document. I am trying to create objects that access the database, and I need in each of these objects a method that returns only an element (ie. getXMLData()). And in the class that created these object, I nee to call the getXML() methods and construct a document. However, I am not looking to create the document if I am not going to use it. In the component class I need to be able to traverse the xml element and read and modify the values. Is there a way to do so with sun's JDK ?
I ve been looking for hours for a method to create an
XML element without the need for the Document.
... I am not looking to create the document if I
am not going to use it.Hi M-A,
Though you have been told the solution, let's stick to your original issue, just for the sake of interest. I gather what you have in mind is finding the answer to the following question: is there a way of creating a document without having to bind it to any data source? The answer is yes. What you might need is the createDocument() method of the DOMImplementation interface which offers lightwight document handling by obviating the need to construct a particular DOM instance. (You could also use the getDOMImplementation() method of the DOMImplementationRegistry interface, but it has bugs.) Here's a sample code:DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
DOMImplementation domImpl = parser.getDOMImplementation();
Document doc = domImpl.createDocument(null, "rootnode", null);The above code produces the following document:<?xml version="1.0" encoding="UTF-8"?>
<rootnode/>You can make this document even skinnier if you pass null values to all three parameters of the createDocument() method, in which case the document will only contain the prolog. I think both the creation and the structure of this document are simple enough for you to use it as some sort of utility (e.g. by putting the code in a separate class) for creating elements. -
How can I access XML attributes in LiveCycle using JavaScript and XPath.
I've tried using:
mynodesFormData.item(i).Name.attributes.getNamedItem("someattr");
Thanks,
IssaI figured it out.
I was simply able to use:
mynodesCRFormData.item(i).Name.englishName.value
mynodesFormData.item(i).Name.attribName.value;
where attribName is the name of the attribute and Name the name of the element.
Thanks,
Issa -
Accessing XML files through java
Can any one explain me the easiest way of accessing XML files from Java.
Hi,
If you want to only access the XML file, use the SAX parser It will be very easy to handle and identify the element and value.
else if u want to change the XML value also, then better go with DOM, Which has very good flexiblity.
use according to the need, let me know if any help is required......
With Cheers
PrasannA -
ACL granularity on XML element
Hello,
when I store a XML in a XMLTYPE (column or table) can I define an ACL on a specific XML element(node)? How fine grained is the ACL restriction? on the whole XML document or even lower to elements and attributes? If it is fine grained to elements can someone provide an example?As far as I know, it is top down...
In http://www.oracle.com/technology/products/database/oracle11g/pdf/xml-db-11g-whitepaper.pdf it is described as follows (the 11g extras):
ENHANCED ACL SECURITY
In Oracle Database 11g, the Oracle XML DB ACL-based security model has been enhanced in a number of ways, including the following:
• ACL Inheritance.
ACL inheritance simplifies the process of defining, managing, and enforcing a common set of security policies across all of the documents stored in Oracle XML DB Repository. These rules can be organization-wide policies or policies specific to certain types of documents. These rules are specified by creating one or more master ACLs. With ACL inheritance it is possible to ensure that all new ACLs must be based on an existing ACL. This ensures that the newly created ACL inherits all of security policies defined by the ACL it is derived from, ensuring that the policies defined by the parent ACL are enforced whenever the new ACL is used.
• DAV ACL Compliance.
The Oracle XML DB ACL model has been enhanced to provide more complete support for the DAV ACL specification. This will allow improved interaction with clients that provide support for the DAV ACL security model.
• User defined ACLs.
In Oracle Database 11g the set of permissions defined by Oracle XML DB can be extended to allow the ACL based security model to be used to secure other kinds of database object.
• Time-sensitive ACLs.
In Oracle Database 11g it is possible to create ACLs that enforce access control polices in a timesensitive manner. This can be used to automatically publish and then expire content, based on rules defined by the ACL. -
Accessing XML View through DBUri
I am having problem in accessing XML View through HttpURI.
Also i need some advise in following such architecture between my app server and DB server.
The problem i am facing is that
1. The query passed through URI does a full table scan, hence poor performance.
2. Not able to query on date/timestamp.
Any help would be appreciated.
ThanksHere is how my output would be..
<log systemID="00XXXABC01" MLN="9999" USN="00XXXPET01" timeStamp="Sun Jun 1 22:00:11 2003" timeZone="BST - Europe/London">
<message type="XXXHealthPage" time="Sun Jun 1 22:00:11 2003" source="XXX">
<text>This is manxx1 machine's HealthPage report</text>
<detail>
<generic_report title="XXX System Health Report">
<emailaddr>[email protected]</emailaddr>
<heading title="System Identification">
<linevalue name="Report_date">Sun Jun 1 22:00:11 2003</linevalue>
<linevalue name="Last_update_time">May 02 2003 22:00:14</linevalue>
</heading>
</generic_report>
</detail>
</message>
</log>
I have underlined the variables that i have to query on.. basically i have to select messages between certain times for a particular system.
am trying a query..
1. http://localhost:8080/oradb/MACLOG/TEST_MACHINE_XML1/ROW/log[@systemid="415444KCT"]
This doesnt work for some reason.. i had to make systemid as a separate element.(@attribute doesnt work)2. i dono how to query for message[@time between to_char(...)]
Any Help..
Maybe you are looking for
-
How to Insert Image in XML publisher Report
Hi Forum, I have created rtf file for xml report and in this i inserted one Image. When run the request from apps environment and while checking the output in excel format, Image is not displaying.. Please advice me. Thanks & Regards, Nag.CH
-
Can't find drivers for Lenovo G50-30 for Windows 7 32-bit
Hi, I can't find drivers for Windows 7x32 bit for my new Lenovo G50-30. Looks like Lenovo support doesn't have them. Am I wrong?
-
hi, i m working on oracle reports 10g , i m making a reports which has many columns when i run report i see that columns r coming down , so how can i set my report to get all column on same line , like A B C D E F G H I J K i want like this A B C D E
-
Is there a way to update the default design-time property (expiration date) of a BPEL Process human task prior to it being instantiated via an API call? How would you update multiple human tasks' expiration date for a single BPEL Process instance? Th
-
Error when try to build listener project
I am trying to build the listener project using VC++6. But I get such errors:<br />//==============================================================/<br />--------------------Configuration: Listener - Win32 Debug--------------------<br />Compiling res