使用LINQ创建XML文档,向其中添加xmlns和xmlns:xsi属性。

17

我尝试使用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 to XML添加它?我尝试了几种方法,但都没有成功,在编译期间会抛出异常。

2个回答

27

请查看如何控制命名空间前缀。你可以使用如下代码:

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”。谢谢! - user1343820

10

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接