通过 LINQ 创建 XML 文档,添加 xmlns,xmlns:xsi

Posted

技术标签:

【中文标题】通过 LINQ 创建 XML 文档,添加 xmlns,xmlns:xsi【英文标题】:Create XML doc by LINQ, add xmlns,xmlns:xsi to it 【发布时间】:2011-09-22 18:10:45 【问题描述】:

我尝试通过 LINQ to XML 创建 GPX XML 文档。

除了向文档添加 xmlns、xmlns:xsi 属性外,一切都很好。通过尝试不同的方式,我得到了不同的异常。

我的代码:

XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-8", "no"),
new XElement("gpx",
new XAttribute("creator", "XML tester"),
new XAttribute("version","1.1"),
new XElement("wpt",
new XAttribute("lat","7.0"),
new XAttribute("lon","19.0"),
new XElement("name","test"),
new XElement("sym","Car"))
));

输出还应包含以下内容:

xmlns="http://www.topografix.com/GPX/1/1" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"

如何通过 Linq 将它添加到 XML?我尝试了几种方法,但都不起作用,编译时出现异常。

【问题讨论】:

【参考方案1】:

见How to: Control Namespace Prefixes。你可以使用这样的代码:

XNamespace ns = "http://www.topografix.com/GPX/1/1";
XNamespace xsiNs = "http://www.w3.org/2001/XMLSchema-instance";
XDocument xDoc = new XDocument(
    new XDeclaration("1.0", "UTF-8", "no"),
    new XElement(ns + "gpx",
        new XAttribute(XNamespace.Xmlns + "xsi", xsiNs),
        new XAttribute(xsiNs + "schemaLocation",
            "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"),
        new XAttribute("creator", "XML tester"),
        new XAttribute("version","1.1"),
        new XElement(ns + "wpt",
            new XAttribute("lat","7.0"),
            new XAttribute("lon","19.0"),
            new XElement(ns + "name","test"),
            new XElement(ns + "sym","Car"))
));

您必须为每个元素指定命名空间,因为这就是使用 xmlns 这种方式的意思。

【讨论】:

我正在寻找这个“xsi:schemaLocation”。谢谢!【参考方案2】:

来自http://www.falconwebtech.com/post/2010/06/03/Adding-schemaLocation-attribute-to-XElement-in-LINQ-to-XML.aspx:

生成以下根节点和命名空间:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:SchemaLocation="http://www.foo.bar someSchema.xsd" 
xmlns="http://www.foo.bar" >
</root>

使用以下代码:

XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
XNamespace defaultNamespace = XNamespace.Get("http://www.foo.bar");
XElement doc = new XElement(
    new XElement(defaultNamespace + "root",
    new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),
    new XAttribute(xsi + "schemaLocation", "http://www.foo.bar someSchema.xsd")
    )
);

请注意 - 如果您想向文档中添加元素,您需要在元素名称中指定 defaultNamespace,否则您会将 xmlns="" 添加到您的元素中。例如,要在上述文档中添加一个子元素“count”,请使用:

xdoc.Add(new XElement(defaultNamespace + "count", 0)

【讨论】:

以上是关于通过 LINQ 创建 XML 文档,添加 xmlns,xmlns:xsi的主要内容,如果未能解决你的问题,请参考以下文章

LINQ to XML概述

如何在 XML 文档中的特定位置添加 XElement

Linq to XML - 更新/更改 XML 文档的节点

C#操作xml文档增删改查(Linq to XML)

LinqToXml  Create Xml file By Dom /Linq

使用 LINQ - C# 在 xml 文件中的特定节点下方添加新元素