2011-06-25 46 views
14

我尝试通过LINQ to XML创建一个GPX XML文档。通过LINQ创建XML文档,添加xmlns,xmlns:xsi到它

除了向文档添加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?我尝试了几种方法,但它不起作用,编译期间出现异常。

回答

22

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这样表示。

+0

我一直在寻找这个“xsi:schemaLocation”。谢谢! –

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 =“”添加到元素中。例如,添加一个子元素“计数”上述文件,使用:

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