I am trying to set up an XPath query for the following xml:
<Assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="Assembly">
<Parts>
<Part>
<PartName>Example</PartName>
</Part>
</Parts>
<Assembly>
I need the PartName element and I have not been able to开发者_高级运维 reference it correctly since the xml declaration is a node and not the usual
<?xml version="1.0"?>
Can someone help me structure my XPath?
Declaring/registering the namespace and using the namespace prefix in your XPath is definitely preferred.
However, if you want an XPath that will work without registering the namespaces, you can use either of the following XPath statements:
/*[local-name()='Assembly' and namespace-uri()='Assembly']
/*[local-name()='Parts' and namespace-uri()='Assembly']
/*[local-name()='Part' and namespace-uri()='Assembly']
/*[local-name()='PartName' and namespace-uri()='Assembly']
This one is shorter, but less "safe" as it only matches against the element names and does not use the namespace as criteria.
/*[local-name()='Assembly']
/*[local-name()='Parts']
/*[local-name()='Part']
/*[local-name()='PartName']
They are long and ugly, but will work.
//Assembly/Parts/Part/PartName
I figured out that I had to set my namespace manager in my C# program that used the XPath:
XmlNamespaceManager nsMgr = new XmlNamespaceManager(Document.NameTable);
nsMgr.AddNamespace("sc", "Assembly");
and the XPath was //sc:Parts/sc:Part/sc:PartName
精彩评论