C# 如何使用';包括';陈述

C# 如何使用';包括';陈述,c#,xml,include,C#,Xml,Include,以前,我曾设法编写代码来生成简单的XML文档,但我需要编写一个具有XML“include”属性的XML文档 这是我需要复制的示例: <?xml version="1.0" encoding="utf-8"?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="./file.xml"/> <data> </data> </

以前,我曾设法编写代码来生成简单的XML文档,但我需要编写一个具有XML“include”属性的XML文档

这是我需要复制的示例:

<?xml version="1.0" encoding="utf-8"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
   <xi:include href="./file.xml"/>
   <data>
   </data>
</document>
有人能推荐一种添加includes语句的简单方法吗

编辑:

如果我使用以下内容,它更接近我的目标,但是添加href属性似乎会导致标签“xi:include”自动更改为“include”


首先,如前所述,您的
include
是一个元素,
href
是一个属性,因此您可以按如下方式创建它:

var doc = new XmlDocument();

var declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(declaration);

var root = doc.CreateElement("document");
root.SetAttribute("xmlns:xi", "http://www.w3.org/2001/XInclude");
doc.AppendChild(root);

var include = doc.CreateElement("xi", "include", "http://www.w3.org/2001/XInclude");
include.SetAttribute("href", "./file.xml");
root.AppendChild(include);

var data = doc.CreateElement("data");
root.AppendChild(data);
但一个简单得多的解决方案是使用LINQtoXML,这是一种更具表现力的API。有很多方法可以使用它,其中一种方法是:

XNamespace include = "http://www.w3.org/2001/XInclude";

var doc = new XDocument(
    new XDeclaration("1.0", "UTF-8", null),
    new XElement("document",
        new XAttribute(XNamespace.Xmlns + "xi", include),
        new XElement(include + "include",
            new XAttribute("href", "./file.xml")
            ),
        new XElement("data")
        )            
    );

在上面的示例中,它抛出了一个argumentexception:元素或属性的本地名称不能为null或空字符串。我尝试将属性文本移动到元素标记,但它没有抛出异常,但xml表示:与其将“/file.xml”添加为href attirute,不如将标签中的“xi:include”更改为“include”代码添加。我不知道如何使用Linq。几个月前刚开始编写代码,但我的老板让我一头扎进了一些小项目(我很喜欢)。谢谢查尔斯。那很好用。现在我将我的示例看作LINQ,我可以看出这是一种更好的构建方法。谢谢你。
var doc = new XmlDocument();

var declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(declaration);

var root = doc.CreateElement("document");
root.SetAttribute("xmlns:xi", "http://www.w3.org/2001/XInclude");
doc.AppendChild(root);

var include = doc.CreateElement("xi", "include", "http://www.w3.org/2001/XInclude");
include.SetAttribute("href", "./file.xml");
root.AppendChild(include);

var data = doc.CreateElement("data");
root.AppendChild(data);
XNamespace include = "http://www.w3.org/2001/XInclude";

var doc = new XDocument(
    new XDeclaration("1.0", "UTF-8", null),
    new XElement("document",
        new XAttribute(XNamespace.Xmlns + "xi", include),
        new XElement(include + "include",
            new XAttribute("href", "./file.xml")
            ),
        new XElement("data")
        )            
    );