问题
I've come from this question, where my first issue was solved: XML Select a single node where the names are repeating It was a namespace issue first.
But now even with the corect NameSpace managing my XPath still returns me null.
I've also checked:
SelectSingleNode return null - even with namespace SelectSingleNode always returns null? XmlDocument.SelectSingleNode and xmlNamespace issue SelectSingleNode returning null for known good xml node path using XPath Why is SelectSingleNode returning null?
But none of 'em helped me. I'm stuck for some hours on this issue. What is wrong with it ?
Thanks for any help.
Sample XML(EDITED: FULL XML)
<?xml version="1.0" encoding="utf-8"?>
<JMF SenderID="InkZone-Controller" Version="1.2" xmlns="http://www.CIP4.org/JDFSchema_1_1">
<Command ID="cmd.00695" Type="Resource">
<ResourceCmdParams ResourceName="InkZoneProfile" JobID="K_41">
<InkZoneProfile ID="r0013" Class="Parameter" Locked="false" Status="Available" PartIDKeys="SignatureName SheetName Side Separation" DescriptiveName="Schieberwerte von DI" ZoneWidth="32">
<InkZoneProfile SignatureName="SIG1">
<InkZoneProfile Locked="false" SheetName="S1">
<InkZoneProfile Side="Front">
<InkZoneProfile Separation="designer P&G 1901" ZoneSettingsX="0.391 "/>
</InkZoneProfile>
</InkZoneProfile>
</InkZoneProfile>
</InkZoneProfile>
</ResourceCmdParams>
</Command>
</JMF>
My code for selecting the specified XML Node:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("C:\\XML\\test.xml");
XmlNode root = xmlDoc.DocumentElement;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("CIP4NS", "http://www.CIP4.org/JDFSchema_1_1");
var parent = root.SelectSingleNode("//CIP4NS:Command/ResourceCmdParams/InkZoneProfile/InkZoneProfile/InkZoneProfile/InkZoneProfile", nsmgr);
XmlElement IZP = xmlDoc.CreateElement("InkZoneProfile");
IZP.SetAttribute("Separation", x.colorname);
IZP.SetAttribute("ZoneSettingsX", x.colorvalues);
parent.AppendChild(IZP);
xmlDoc.Save("C:\\XML\\test.xml");
回答1:
Your XML has default namespace which descendant elements without prefix implicitly inherits from the ancestor. That implies, not only the root element but all elements mentioned in your XPath are in the same default namespace, hence need to be referenced by using the same prefix :
//CIP4NS:Command/CIP4NS:ResourceCmdParams/CIP4NS:InkZoneProfile/CIP4NS:InkZoneProfile/CIP4NS:InkZoneProfile/CIP4NS:InkZoneProfile
来源:https://stackoverflow.com/questions/35676471/selectsinglenode-returns-null-even-with-namespace-managing