简体   繁体   中英

Java DOM XML Parser with chaning namespaces

I do REST calls to a WebService and receive always XML as response. Then i'm parsing that XML und filling Java objects with those informations. The Problem is that the element-tags could have different namespaces, like this:

  <ns:title>....</ns:title>

or

  <ns2:title>....<ns2:title>

or

  <title>...<title>

EDIT: And the namespace URIs look like this:

 <ns2:feed xmlns="http://www.example.com/routing1/routing2" 
 xmlns:ns2="http://www.w3.org/../Atom" 
 xmlns:ns3="http://www.example.com/routing1/routing2"
 xmlns:ns4="http://purl.org/routing1/routing2/1.0">

So therefore i changed the method element.getElementsByTagNameNS("specifiedNamespace", "title") to element.getElementsByTagNameNS("*", "title") . Is that okay to match all namespace, because i have also the case that the element-tag doesn't have a namespace like the third example <title>..</title> ..

Is there a better procedure, to solve that problem? Or is it okay to solve it like, how i do it?

Thanks.

EDIT: 2 response examples

1.

<ns2:feed xmlns="http://www.example.com/routing1/routing2" xmlns:ns2="http://www.w3.org/../Atom" xmlns:ns3="http://www.example.com/routing1/routing2" xmlns:ns4="http://purl.org/routing1/routing2/1.0">
  ...
  <ns2:someTag1>..</ns2:someTag1>
  <ns2:title>title</ns2:title>
  <entry>...</entry>
  ....
</ns2:feed>

2

<ns2:feed xmlns="http://www.w3.org/../Atom" xmlns:ns2="http://www.example.com/routing1/routing2" xmlns:ns3="http://www.example.com/routing1/routing2" xmlns:ns4="http://purl.org/routing1/routing2/1.0">
  ...
  <someTag1>..<someTag1>
  <title>title<title>
  <ns2:entry>...</ns2:entry>
  ....
</ns2:feed>

Your title elements have the same namespace in both of your examples.

In the first example, you have:

 xmlns:ns2="http://www.w3.org/../Atom" 

and

 <ns2:title>title</ns2:title>

so this means that title is in the http://www.w3.org/../Atom namespace.

In the second example, you have:

 xmlns="http://www.w3.org/../Atom"

and

 <title>title<title>

so here again title is in the http://www.w3.org/../Atom namespace.


The prefixes are different (the second example isn't using a prefix for title ), but the namespace is the same.

This means that you should be able to use:

element.getElementsByTagNameNS("http://www.w3.org/../Atom", "title")

and it should successfully select the title element, even if the prefixes change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM