我们获得了一个示例文档,并且需要能够准确地为供应商重现文档的结构.但是,我对 C# 如何处理命名空间有点迷茫.以下是文档示例:
We were given a sample document, and need to be able to reproduce the structure of the document exactly for a vendor. However, I'm a little lost with how C# handles namespaces. Here's a sample of the document:
<?xml version="1.0" encoding="UTF-8"?>
<Doc1 xmlns="http://www.sample.com/file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sample.com/file/long/path.xsd">
<header>
<stuff>data</stuff>
<morestuff>data</morestuff>
</header>
</Doc1>
我通常会加载一个空白文档,然后开始填充它:
How I'd usually go about this is to load a blank document, and then start populating it:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Doc1></Doc1>");
// Add nodes here with insert, etc...
一旦开始创建文档,如何将命名空间和架构放入 Doc1 元素中?如果我从 Doc1 元素中的命名空间和模式开始,将它们包含在 LoadXml() 中,那么 所有 子元素上都有命名空间——这是一个禁忌.文档被拒绝.
Once I get the document started, how do I get the namespace and schema into the Doc1 element? If I start with the namespace and schema in the Doc1 element by including them in the LoadXml(), then all of the child elements have the namespace on them -- and that's a no-no. The document is rejected.
因此,换句话说,我必须完全按照所示制作它.(而且我宁愿不只是在 C# 中编写文本到文件并希望它是有效的 XML).
So in other words, I have to produce it EXACTLY as shown. (And I'd rather not just write text-to-a-file in C# and hope it's valid XML).
你应该这样试试
XmlDocument doc = new XmlDocument();
XmlSchema schema = new XmlSchema();
schema.Namespaces.Add("xmlns", "http://www.sample.com/file");
doc.Schemas.Add(schema);
不要忘记包含以下命名空间:
Do not forget to include the following namespaces:
using System.Xml.Schema;
using System.Xml;
这篇关于在 C# 中使用命名空间创建特定的 XML 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!