我有这个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 0.36 0.097 0.058 0 0 0 0 0 0 0 0 0.178 0.394 0.201 0.088"/>
我正在尝试在节点之后追加元素,但我无法。用我的代码我试图用XPath选择节点:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(GlobalVars.FullPath);
xmlDoc.SelectSingleNode("JMF/Command/ResourceCmdParams/InkZoneProfile/InkZoneProfile/InkZoneProfile/InkZoneProfile");
XmlElement IZP = xmlDoc.CreateElement("InkZoneProfile");
IZP.SetAttribute("Separation", x.colorname);
IZP.SetAttribute("ZoneSettingsX", x.colorvalues);
xmlDoc.DocumentElement.AppendChild(IZP);
xmlDoc.Save(GlobalVars.FullPath);
但是它没有追加到我选择的节点 - 而是继续追加到最后一行。 我如何追加这个具体职位?我错过了一些论点吗?
感谢。
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(GlobalVars.FullPath);
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(GlobalVars.FullPath);
答案 0 :(得分:1)
xmlDoc.SelectSingleNode("JMF/Command/ResourceCmdParams/InkZoneProfile/InkZoneProfile/InkZoneProfile/InkZoneProfile");
的返回值。 XmlNode.SelectSingleNode不会更改XmlDocument
中的任何内容 - 它会在指定路径下返回XmlNode
。xmlDoc.DocumentElement.AppendChild
会在end of the root element之前附加元素,并且您的根元素为<JMF SenderID="InkZone-Controller" Version="1.2" xmlns="http://www.CIP4.org/JDFSchema_1_1">
。所以你应该保存SelectSingleNode
的结果并将孩子附加到它:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(GlobalVars.FullPath);
var parent = xmlDoc.SelectSingleNode("JMF/Command/ResourceCmdParams/InkZoneProfile/InkZoneProfile/InkZoneProfile/InkZoneProfile");
XmlElement IZP = xmlDoc.CreateElement("InkZoneProfile");
IZP.SetAttribute("Separation", x.colorname);
IZP.SetAttribute("ZoneSettingsX", x.colorvalues);
parent.AppendChild(IZP);
xmlDoc.Save(GlobalVars.FullPath);