在 C# 中使用命名空间创建特定的 XML 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/443250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a specific XML document using namespaces in C#
提问by Clinton Pierce
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:
我们得到了一个示例文档,我们需要能够准确地为供应商重现文档的结构。但是,我对 C# 处理命名空间的方式有点迷茫。这是文档的示例:
<?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...
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 allof the child elements have the namespace on them -- and that's a no-no. The document is rejected.
启动文档后,如何将命名空间和模式放入 Doc1 元素中?如果我从 Doc1 元素中的命名空间和架构开始,将它们包含在 LoadXml() 中,那么所有子元素都具有命名空间——这是一个禁忌。文件被拒绝。
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).
所以换句话说,我必须完全如图所示制作它。(而且我宁愿不只是在 C# 中将文本写入文件并希望它是有效的 XML)。
采纳答案by Dimi Takis
You should try it that way
你应该这样试试
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;
回答by Pop Catalin
If you are using Visual Studio 2008 in the Samples folder you'll find a sample addin that let's you paste a XML fragment as Linq2XML code.
如果您在 Samples 文件夹中使用 Visual Studio 2008,您将找到一个示例插件,可让您将 XML 片段粘贴为 Linq2XML 代码。
Scott Hanselmanhas a blog postwith the details.
Scott Hanselman有一篇包含详细信息的博客文章。
I think this is the quickest way to go from a sample XML doc to C# code that creates it.
我认为这是从示例 XML 文档到创建它的 C# 代码的最快方法。
回答by mathifonseca
I personally prefer to use the common XmlElement and its attributes for declaring namespaces. I know there are better ways, but this one never fails.
我个人更喜欢使用通用的 XmlElement 及其属性来声明命名空间。我知道有更好的方法,但这个方法永远不会失败。
Try something like this:
尝试这样的事情:
xRootElement.SetAttribute("xmlns:xsi", "http://example.com/xmlns1");