最佳答案
在生成的 XML 中,p1 是一个命名空间。您发布的代码(在屏幕截图中)定义了命名空间“xsi”,我不确定为什么您的结果会生成 p1,除非您将 xsi 重命名为未显示的某处。
XmlDocument doc = new XmlDocument();
XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
XmlElement rootnode = doc.CreateElement("BMECAT");
doc.InsertBefore(declaire, doc.DocumentElement);
doc.AppendChild(rootnode);
rootnode.SetAttribute("version", "2005");
XmlAttribute atr = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
atr.Value = "http://www.adlnet.org/xsd/adlcp.vlp3";
rootnode.SetAttributeNode(atr);
rootnode.Attributes.Append(atr);
在您的代码中:
XmlAttribute atr = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
“xsi”是它生成的命名空间的名称,你可以在那里控制它。这导致:
<?xml version="1.0" encoding="utf-8"?>
<BMECAT version="2005" xsi:schemaLocation="http://www.adlnet.org/xsd/adlcp.vlp3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
我不确定您的代码是否与您提供的结果文件相匹配。当我运行代码时,我得到了预期的“xsi”。如果我在那里将“xsi”设置为 null,它会使用一个默认名称,在我的例子中是 d1p1。 “xsi”的所有实例都替换为“d1p1”。这让我相信代码可能与生成结果的代码略有不同。我不知道“d1p1”来自哪里,它可能是生成的默认命名空间。这似乎是一个常见的默认值 ( Remove "d1p1" namespace prefix in DataContractSerializer XML output )。在您提供的代码中,如果您将“xsi”更改为“p1”,您将得到结果。
我可能会建议改用这种方法:
How to Add schemaLocation attribute to an XML document
在这里,您将针对 XmlElement 根节点使用已接受的答案。
XmlElement.SetAttributeValue (localname, prefix, namespace, value)
关于c# - 使用 C# 使用 XmlDocument 在根节点中获取架构位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59054614/