Creating a specific XML document using namespaces in C#

我们两清 提交于 2020-01-19 03:38:20

问题


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...

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.

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).


回答1:


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;



回答2:


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.

Try something like this:

xRootElement.SetAttribute("xmlns:xsi", "http://example.com/xmlns1");



回答3:


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.

Scott Hanselman has a blog post with the details.

I think this is the quickest way to go from a sample XML doc to C# code that creates it.



来源:https://stackoverflow.com/questions/443250/creating-a-specific-xml-document-using-namespaces-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!