创建使用名称空间在C#中特定的XML文档 [英] Creating a specific XML document using namespaces in C#

查看:84
本文介绍了创建使用名称空间在C#中特定的XML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们分别获得了示例文档,并需要能够再现文档的结构完全相同的厂商。不过,我用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元素?如果我通过包括他们在loadXML的(),然后开始在DOC1元素的名称空间和模式的所有的子元素都对他们的命名空间 - 这是一个禁忌。该文件将被拒绝。

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文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆