-3

发生了什么\有什么区别?我正在尝试从 XML 文件返回特定节点。

XML 文件:

  <?xml version="1.0" encoding="utf-8"?>
    <JMF SenderID="InkZone-Controller" Version="1.2">
      <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>
            </InkZoneProfile>
          </InkZoneProfile>
        </ResourceCMDParams>
      </Command>
<InkZoneProfile Separation="Cyan" ZoneSettingsX="0 0,005 " />
    </JMF>

代码:

           XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("C:\\test\\test.xml");
            XmlNode root = xmlDoc.DocumentElement;
            var parent = root.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("C:\\test\\test.xml");

var 父级返回 null。我已经调试过,root 和 xmlDoc 在它们的内部文本中有 XML 内容。但是,在此处进行的测试(由用户 @har07 对上一个问题进行: SelectSingleNode 即使使用命名空间管理也返回 null 工作没有问题 。https ://dotnetfiddle.net/vJ8h9S

这两者有什么区别?它们基本上遵循相同的代码,但一个有效,另一个无效。
调试时,我发现 root.InnerXml 本身加载了内容(与 XmlDoc.InnerXml 相同)。但是 InnerXml 没有实现 SelectSingleNode 的方法。我相信如果我将它保存到一个字符串中,我可能会失去缩进等。

有人可以告诉我有什么区别或有什么问题吗?谢谢 !XML 示例:https ://drive.google.com/file/d/0BwU9_GrFRYrTUFhMYWk5blhhZWM/view?usp=sharing

4

1 回答 1

1

SetAttribute不要为您自动转义字符串。因此它使您的 XML 文件无效。

从 MSDN 关于XmlElement.SetAttribute

任何标记,例如被识别为实体引用的语法,都被视为文字文本,并且在写出时需要由实现正确转义

在您的代码中查找所有行包含SetAttribute并用于SecurityElement.Escape转义该值。

例如:更改这些行:

IZP.SetAttribute("Separation", x.colorname);
IZP.SetAttribute("ZoneSettingsX", x.colorvalues);

至:

using System.Security;

IZP.SetAttribute("Separation", SecurityElement.Escape(x.colorname));
IZP.SetAttribute("ZoneSettingsX", SecurityElement.Escape(x.colorvalues));

如果一个属性的名称包含任何<>"'&你也必须像值一样转义它。

笔记:

您必须删除使用旧代码创建的当前 xml,因为它无效,加载时会导致异常。

于 2016-02-28T02:35:29.787 回答