c# - 使用 C# 使用 XmlDocument 在根节点中获取架构位置

标签 c# xml namespaces

我必须从数据表中填写一个 XML 文件,我的问题是我必须在根节点中获取 schemaLocation,为此我使用下面的代码,然后我得到了这个结果,我不知道 p1 在哪里来自 enter image description here enter image description here

最佳答案

在生成的 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/

相关文章:

c# - 无法在 Entity Framework 中使用 AddRange 自动生成 IDENTITY

c# - 使用证书的相互 SSL 的 WCF 身份验证错误

c# - 从 Angular 2 到 ASP.NET ApiController 的 Http.post

C# 我应该在连接池中保持打开连接吗

java - android.view.inflateexception 二进制 xml 文件行 #1 错误膨胀类 android.widget.relativeLayout

XML 数据类型转换

c++ - 在类中定义的友元函数的完全限定名称是什么?

namespaces - 如何在 C++/CLI 应用程序中正确设置根命名空间属性?

xml - 将数据存储为 XML

python - 如何从模块命名空间获取全局变量?