0

I have to extract attr value from such XML:

<FIXML xmlns="http://www.fixprotocol.org/FIXML-5-0-SP2">
    <TAG attr="value">
       ...  
    </TAG>
</FIXML>

and try to use such Java code

XPathExpression expression = XPathExpressionFactory.createXPathExpression("/FIXML/TAG/@attr");
XmlPayloadConverter converter = new DefaultXmlPayloadConverter();
Node node = converter.convertToNode(xmlStr);
Object result = expression.evaluateAsString(node);

Unfortunately, the result value is always empty here. If I remove namespace attr xmlns="http://www.fixprotocol.org/FIXML-5-0-SP2" the code works as expected (result has value string).

How to ignore the namespace in my Java code example?

UPDATE: looks like I have to use XPath local-name() function in my expression but how to use it practically in my case?

SOLUTION: in my case the correct XPath exprtssion is "/*[local-name()='FIXML']/*[local-name()='TAG']/@attr"

Andriy Kryvtsun
  • 3,220
  • 3
  • 27
  • 41
  • 1
    Another possible duplicate: https://stackoverflow.com/questions/3939636/how-to-use-xpath-on-xml-docs-having-default-namespace – Daniel Haley May 09 '18 at 16:47

1 Answers1

1

Something similar was posted/answered here: How to retrieve namespaces in XML files using Xpath

An alternative would be to forget about associating a prefix with that namespace, and just make your path namespace-free. You can do this by using the local-name() function whenever you need to refer to an element whose namespace you don't know. For example:

//*[local-name() = 'Element']
EdHayes3
  • 1,777
  • 2
  • 16
  • 31
  • Could you provide correct XPath expression for my case? I already tried to use `local-name()` but constantly got XPath compilation errors. – Andriy Kryvtsun May 09 '18 at 16:17
  • When I was dealing with trying to extract an attributes value using Transact SQL, I played around with it for hours until I found the solution. Unfortunately I can't help you with Java. With that said, I don't actually see any namespace on your XML. That looks like where "a" is the namespace. Your xmlns attribute looks like its defining a namespace in an invalid way. – EdHayes3 May 09 '18 at 16:23
  • Namespace definition: ` African ` – EdHayes3 May 09 '18 at 16:27
  • 1
    @AndriyKryvtsun - Try the xpath `/*[local-name()='FIXML']/*[local-name()='TAG']/@attr`. @EdHayes3 - The xmlns is fine. The namespace uri does not have to be bound to a prefix. When it's not bound, it's usually referred to as a ["default namespace"](https://www.w3.org/TR/REC-xml-names/#defaulting). – Daniel Haley May 09 '18 at 16:44