473,881 Members | 1,700 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

java xerces xpath fails with namespace

I have a simple program to run xpath with xerces 1_2_7

XPathFactory factory = XPathFactory.ne wInstance();
XPath xPath = factory.newXPat h();
XPathExpression xp = xPath.compile(s trXpr);
System.out.prin tln(xp.evaluate (new InputSource(new
FileInputStream ("a.xml")))) ;

if a.xml is
<?xml
version="1.0"?> <root><parent>< son>theTextValu e</son></parent></root>

and strXpr is /root/parent/son/text()
I got correct value back "theTextVal ue".

But if parent is with namespace, such as soap message, it always fails,
eg.:<?xml version="1.0"?> <soap:Envelop e
xmlns:soap="htt p://schemas.xmlsoap .org/soap/envelope/"
xmlns:xsd="http ://www.w3.org/2001/XMLSchema"
xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance"><soap :Body><son>theV alue</son>
</soap:Body></soapEnvelope>

strXpr is /soap:Envelope/soap:Body/son/text()

empty string was returned...

Any suggestion are welcome.

Thanks.

Feb 10 '06 #1
18 7743
XPath is namespace-sensitive. To correctly search a namespaced document,
you must use prefixes in your XPath and provide bindings from those
prefixes to the appropriate namespace URIs.

If you really insist on doing a namespace-insensitive search, it's
possible by using kluge-arounds such as node()[name()="foo"] ... but
REALLY not recommended. Namespaces are used because they're a meaningful
distinction. Don't attempt to ignore or bypass them.
Feb 10 '06 #2
Would you please more detail? How to specify prefix in xpath?

eg. my xml file is:
?xml version='1.0' encoding='UTF-8'?>
<soap:Envelop e xmlns:soap="htt p://schemas.xmlsoap .org/soap/envelope/"
xmlns:xsd="http ://www.w3.org/2
001/XMLSchema"
xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance"><soap :Body>testtext</soap:Body>
</soap:Envelope>

and my xpath is:
//soap:Envelope/soap:Body/text()
or
//Envelope/Body/text()

all no result back....

Thanks.

Feb 10 '06 #3
jacksu wrote:
and my xpath is:
//soap:Envelope/soap:Body/text()
or
//Envelope/Body/text()


The second won't work. The first will, *if* you've told your XPath
processor that the soap: prefix maps to
"http://schemas.xmlsoap .org/soap/envelope/"

How you do that depends on the processor. If you're using the XPath
within an XSLT stylesheet, you just need to make sure soap: has been
properly declared as a namespace at a point where it will be inherited
by the statement which is executing the XPath; the usual practice is to
define most namespaces all the way up at the top-level xsl:stylesheet
element to make sure they're available throughout the document.

If you're using an XPath API of some sort, check its docs to find out
how to tell it the mapping between prefixes and namespace URIs.
Feb 10 '06 #4
jacksu wrote:

Hi
//soap:Envelope/soap:Body/text()
or
//Envelope/Body/text()

all no result back....


Hmm... Shold fail with a loud bang, if you used a prefix in the XPath
but did not bind it to a namespace.

Try look around in the documentation for that XPath evaluation thing (I
don't know it), for something called a namespace environment, context or
something like that. When you found it, you will need to call something
like bind("soap", "http://namespaceURI/of/SOAP") on it before evaluating.
Soren
Feb 10 '06 #5


jacksu wrote:
I have a simple program to run xpath with xerces 1_2_7

XPathFactory factory = XPathFactory.ne wInstance();
XPath xPath = factory.newXPat h();
XPathExpression xp = xPath.compile(s trXpr);
System.out.prin tln(xp.evaluate (new InputSource(new
FileInputStream ("a.xml")))) ;


That looks like Java using the JAXP XPath API from Java 1.5 to me.
However Xerces-Java 2.6 or 2.7 might implement that, but rather not 1_2_7.

If you want to use namespaces then you need to pass in an object
implementing javax.xml.names pace.NamespaceC ontext that implements the
methods to resolve prefixes to namespace URIs and the other way round.
Then do
xp.setNamespace Context(yourObj ectImplementing NamespaceContex t);
before you compile or evaluate expressions.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Feb 10 '06 #6
Martin Honnen wrote:
If you want to use namespaces then you need to pass in an object
implementing javax.xml.names pace.NamespaceC ontext that implements the
methods to resolve prefixes to namespace URIs and the other way round.


See, for example,
http://xml.apache.org/xalan-j/xpath_...mespacecontext
Feb 10 '06 #7
Working example for the Apache/Xalan code:

public static void main(String[] args) {
String strXpr = "/a:foo/a:bar";
XPathFactory factory = XPathFactory.ne wInstance();
XPath xPath = factory.newXPat h();
try {
// Anonymous hardcoded Namespace Context:
NamespaceContex t MyNSC=new NamespaceContex t() {
public String getNamespaceURI (String prefix) {
if (prefix.equals( "a")) return "urn:a";
else return XMLConstants.NU LL_NS_URI;
}
public String getPrefix(Strin g namespace) {
return null; // Just dummied out; Xalan doesn't need it.
}
public Iterator getPrefixes(Str ing namespace) {
return null; // Just dummied out; Xalan doesn't need it.
}
};

xPath.setNamesp aceContext(myns c);
XPathExpression xp = xPath.compile(s trXpr);
System.out.prin tln(xp.evaluate (
new InputSource(new FileInputStream ("a.xml")))) ;
} catch (Exception e) {
e.printStackTra ce();
}
}
Feb 10 '06 #8
Whups. Typo crept in while recopying this into the newsgroup; obviously,
MyNSC and mynsc were supposed to be the same variable. That's what I get
for trying to simplify the example on the fly.
Feb 10 '06 #9
Thanks a lot.

It works fine in pure with-prefix mode, but seems have problem in
with-prefix/without-prefix mixed mode
such as:
<?xml version='1.0' encoding='UTF-8'?><soap:Envel ope
xmlns:soap="htt p://schemas.xmlsoap .org/soap/envelope/"
xmlns:xsd="http ://www.w3.org/2001/XMLSchema"
xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance"><soap :Body><mynode
xmlns="http://mynamespace">my text</mynode></soap:Body></soap:Envelope>

I tried:
//soap:Envelope/soap:Body/mynode/text()

If I gives prefix to mynode, then everything works fine.

Any more suggestion?

Thanks.

Feb 10 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4226
by: Michael | last post by:
Hello I am trying to write a Java-Program which converts a XML-file in a HTML. It should take the Transformation-file from the XML-file itself. Below find a possible XML-file: <?xml version="1.0" encoding="UTF-8"?> <!-- edited with XMLSPY v5 rel. 3 U (http://www.xmlspy.com) by Michael Herren (private) -->
0
6821
by: Ravi Tallury | last post by:
Hi We are having issues with our application, certain portions of it stop responding while the rest of the application is fine. I am attaching the Java Core dump. If someone can let me know what the issue is. Thanks Ravi
0
4112
by: Brian | last post by:
I am having alot of trouble getting a XML document validated with a schema. I got a sample document and schema off of w3schools.com, which passed an online xml validator: http://tools.decisionsoft.com/schemaValidate.html. I cannot, however, get them validated programmatically. The documents are:
5
14066
by: Aleksandar Matijaca | last post by:
Hi there, I am in some need of help. I am trying to parse using the apache sax parser a file that has vaid UTF-8 characters - I keep end up getting a sun.io.MalformedInputException error. This is my code:
0
1249
by: S ML | last post by:
Hello, I use the Xerces XS* classes to parse and get the definition of an XML schema. I don't seem to find a way to get the namespace prefixes using this framework and I read somewhere that the reason for that is possibly because, the same namespace URI can have multiple prefixes. But the problem I am facing is, the xpath definition specified for key, keyref and unique elements use the namespace prefixes and these are not converted to the...
3
2767
by: ciaran.mchale | last post by:
Hi folks, I downloaded the binary version of Xerces C++ 2.7.0 for Windows and am using it to help me get up to speed with XML and XML Schema. So please excuse me if this is a "novice" question. In the samples/data directory, I ran the following command for all the files: DOMPrint -n -s -f -v=always <filename>
3
4984
by: Jason Mobarak | last post by:
Hello -- I'm attempting to get a handle on how to do xpath queries with System.Xml -- so far the biggest hurdle has been how to deal with a default namespace. If I use the test xml: <?xml version="1.0" encoding="utf-8" ?> <thing xmlns="urn:thing-schema-v1"> <foo>foo thing</foo> <bar>bar thing</bar>
6
7301
by: J.Marsch | last post by:
I must be completely losing my mind. I have some code that writes to config files. It works great with app.config files, but fails miserably with web.config files. For the life of me, I cannot figure out what is going on here. I have taken it all the way back to just selecting the configuration node (top level node), and it fails! How can this line fail (returns null)??
2
2366
by: Boris Kolpackov | last post by:
Hi, I am pleased to announce the availability of Apache Xerces-C++ 3.0.0. Xerces-C++ is an open-source validating XML parser written in a portable subset of C++. It provides DOM (level 1, 2, and 3), SAX, and SAX2 APIs and supports validation of XML documents against DTD and XML Schema. This release includes a large number of new features, bug fixes, and clean-ups, including:
0
9930
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11103
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10720
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10403
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9555
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7953
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5978
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4597
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.