2011-06-25 25 views
14

Tôi cố gắng tạo một tài liệu XML GPX bằng LINQ to XML.Tạo tài liệu XML bằng LINQ, thêm xmlns, xmlns: xsi vào nó

Mọi thứ hoạt động tốt, ngoại trừ việc thêm thuộc tính xmlns, xmlns: xsi vào tài liệu. Bằng cách thử nó theo cách khác, tôi nhận được các ngoại lệ khác nhau.

Mã của tôi:

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")) 
)); 

Sản lượng cũng nên chứa này:

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" 

Làm thế nào tôi có thể thêm nó bằng LINQ to XML? Tôi đã thử một số cách nhưng nó không hoạt động, ngoại lệ trong thời gian biên dịch.

Trả lời

22

Xem How to: Control Namespace Prefixes. Bạn có thể sử dụng mã như thế này:

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")) 
)); 

Bạn cần phải xác định không gian tên cho mỗi phần tử, bởi vì đó là những gì sử dụng xmlns cách này nghĩa là gì.

+0

Tôi đã tìm chính xác cho "xsi: schemaLocation" này. Cảm ơn bạn! –

10

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

Để tạo nút gốc sau và không gian tên:

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

Sử dụng đoạn mã sau:

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") 
    ) 
); 

Hãy nhận biết - nếu bạn muốn thêm các yếu tố để các tài liệu, bạn cần chỉ định defaultNamespace trong tên phần tử hoặc bạn sẽ nhận được xmlns = "" được thêm vào phần tử của bạn. Ví dụ: để thêm phần tử con "đếm" vào tài liệu ở trên, hãy sử dụng:

xdoc.Add(new XElement(defaultNamespace + "count", 0) 
Các vấn đề liên quan