2011-06-25 17 views
14

मैं LINQ से XML तक एक GPX XML दस्तावेज़ बनाने का प्रयास करता हूं।LINQ द्वारा एक्सएमएल दस्तावेज़ बनाएं, 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 से इसे जोड़ सकते हैं? मैंने कई तरीकों की कोशिश की लेकिन यह काम नहीं करता है, संकलन समय के दौरान अपवाद।

उत्तर

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

ध्यान रखें - आप के लिए तत्वों जोड़ना चाहते हैं दस्तावेज़, आपको तत्व नाम में डिफ़ॉल्ट नामस्थान निर्दिष्ट करने की आवश्यकता है या आपको xmlns = "" आपके तत्व में जोड़ा जाएगा। उदाहरण के लिए, उपयोग ऊपर दस्तावेज़ में चाइल्ड तत्व "गिनती" जोड़ने के लिए:

xdoc.Add(new XElement(defaultNamespace + "count", 0) 
संबंधित मुद्दे