1

I have been working with XML files with default namespaces. Thanks to the contributors to StackOverflow, I have been able to parse them with

# Python
xmlns = docroot.namespaceURI
xmldoc.SetProperty("SelectionNamespaces", 'xmlns:a=" + xmlns + '"')

But now I have a different XML doc (this is a generic snippet)

<ns1:overall_1 xmlns:ns1="uri1_1:uri1_2" xmlns:ns2="uri2_1:uri2_2">
  <ns1:tag1>
    <ns1:tag2>value1_1</ns1:tag2>
    <ns2:tag3>value2_1</ns2:tag3>
  </ns1:tag1>
</ns1:overall_1>

and attempts to use SelectSingleNode("ns1:tag1") or are rejected with "Namespace not found". I use relative xml paths within the file, so I'm not sure about use a '/' anchor.

So how can I use SelectSingleNode() or SelectNodes() with these namespaces? (There are a lot of each namespace in the file.) BTW, docroot.namespaceURI returns an empty string, since there is no default namespace. Also, if xmldoc.SetProperty() is the correct call, how does that work with multiple namespaces? I see the VBA way in 'SelectSingleNode' XPath query from XML with multiple Namespaces In Python, would that become

xmlns_1_and_2 = 'xmlns:ns1="uri1_1:uri1_2" xmlns:ns2="uri2_1:uri2_2"'
xmldoc.SetProperty("SelectionNamespaces", xmlns_1_and_2 )

And how can I read the named namespaces in the first line (so I don't have to hardcode them), akin to how I can read the default namespace with docroot.namespaceURI?

1
  • 2
    Single or multiple. Default or not. It's all the same: Register the namespace prefixes as shown in the duplicate link, and use the prefixes in the XPath. Commented Jan 14, 2022 at 17:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.