C# XML 属性创建不正确

本文关键字:不正确 创建 属性 XML | 更新日期: 2023-09-27 18:36:11

我正在以编程方式创建一个节点,但是其中一个属性与我在代码中指定的不同:

                XmlNode xResource = docXMLFile.CreateNode(XmlNodeType.Element, "resource", docXMLFile.DocumentElement.NamespaceURI);
                XmlAttribute xRefIdentifier = docXMLFile.CreateAttribute("identifier");
                XmlAttribute xRefADLCP = docXMLFile.CreateAttribute("adlcp:scormtype");
                XmlAttribute xRefHREF = docXMLFile.CreateAttribute("href");
                XmlAttribute xRefType = docXMLFile.CreateAttribute("type");
                xRefIdentifier.Value = "RES-" + strRes;
                xRefADLCP.Value = "sco";
                xRefHREF.Value = dataRow["launch_url"].ToString().ToLower();
                xRefType.Value = "webcontent";
                xResource.Attributes.Append(xRefIdentifier);
                xResource.Attributes.Append(xRefADLCP);
                xResource.Attributes.Append(xRefHREF);
                xResource.Attributes.Append(xRefType);

这最终会创建如下所示的行。 请注意,'adlcp:scormtype' 已经变成了 'scormtype',这不是我指定的。 任何想法如何让它显示我在创建属性中放置的内容?

 <resource identifier="RES-CDA68F64B849460B93BF2840A9487358" scormtype="sco" href="start.html" type="webcontent" />

C# XML 属性创建不正确

这可能是此覆盖 CreateAttribute 与保存文档相结合的预期行为:

命名空间 URI 保持为空,除非前缀是可识别的内置前缀,例如 xmlns。在这种情况下,命名空间 URI 的值为 http://www.w3.org/2000/xmlns/。

使用另一个重写 XmlDocument.CreateAttribute 来指定命名空间和前缀:

XmlAttribute xRefADLCP = docXMLFile.CreateAttribute(
     "adlcp","scormtype", "correct-namespace-here");

您可以直接设置属性的前缀,而不是尝试创建与前缀内联的属性。

XmlAttribute xRefADLCP = docXMLFile.CreateAttribute("scormtype");
// ...
xRefADLCP.Prefix = "adlcp";
xRefADLCP.Value = "sco";