XPath queries are aware of namespaces in an XML document and can use namespace prefixes to qualify element and attribute names. Qualifying element and attribute names with a namespace prefix limits the nodes returned by an XPath query to only those nodes that belong to a specific namespace.
The local-name function returns a string representing the local name of the first node in a given node-set.
You can use the local-name()
XPath function. Instead of selecting a node like
/path/to/x:somenode
you can select all nodes and filter for the one with the correct local name:
/path/to/*[local-name() = 'somenode']
You can do the same In XPath2.0 in a less verbose syntax:
/path/to/*:somenode
Or you can use name():
/path/to/*[name() = 'somenode']
Or only search attributes:
//*[@attribute="this one"]
If you open the xml as a powershell object, it ignores the namespaces:
[xml]$xml = get-content file.xml
$xml.path.to.somenode
You could use Namespace = false on a XmlTextReader
[TestMethod]
public void MyTestMethod()
{
string _withXmlns = @"<?xml version=""1.0"" encoding=""utf-8""?>
<ParentTag xmlns=""http://anyNamespace.com"">
<Identification value=""ID123456"" />
</ParentTag>
";
var xmlReader = new XmlTextReader(new MemoryStream(Encoding.Default.GetBytes(_withXmlns)));
xmlReader.Namespaces = false;
var content = XElement.Load(xmlReader);
XElement elem = content.XPathSelectElement("/Identification");
elem.Should().NotBeNull();
elem.Attribute("value").Value.Should().Be("ID123456");
}
with :
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With