問題描述
我們獲得了一個(gè)示例文檔,并且需要能夠準(zhǔn)確地為供應(yīng)商重現(xiàn)文檔的結(jié)構(gòu).但是,我對(duì) C# 如何處理命名空間有點(diǎn)迷茫.以下是文檔示例:
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>
我通常會(huì)加載一個(gè)空白文檔,然后開始填充它:
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...
一旦開始創(chuàng)建文檔,如何將命名空間和架構(gòu)放入 Doc1 元素中?如果我從 Doc1 元素中的命名空間和模式開始,將它們包含在 LoadXml() 中,那么 所有 子元素上都有命名空間——這是一個(gè)禁忌.文檔被拒絕.
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).
推薦答案
你應(yīng)該這樣試試
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;
這篇關(guān)于在 C# 中使用命名空間創(chuàng)建特定的 XML 文檔的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!