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

Tom*_*Tom 14 c# xml linq gpx

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

除了将xmlns,xmlns:xsi属性添加到doc之外,一切都很好.通过尝试不同的方式,我得到不同的例外.

我的代码:

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"))
));
Run Code Online (Sandbox Code Playgroud)

输出还应包含:

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"
Run Code Online (Sandbox Code Playgroud)

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

svi*_*ick 23

请参见如何:控制命名空间前缀.你可以使用这样的代码:

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"))
));
Run Code Online (Sandbox Code Playgroud)

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


And*_*bel 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>
Run Code Online (Sandbox Code Playgroud)

使用以下代码:

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")
    )
);
Run Code Online (Sandbox Code Playgroud)

请注意 - 如果要向文档添加元素,则需要在元素名称中指定defaultNamespace,否则将在元素中添加xmlns ="".例如,要将子元素"count"添加到上述文档,请使用:

xdoc.Add(new XElement(defaultNamespace + "count", 0)
Run Code Online (Sandbox Code Playgroud)