簡體   English   中英

通過LINQ創建XML文檔,向其添加xmlns,xmlns:xsi

[英]Create XML doc by LINQ, add xmlns,xmlns:xsi to it

我嘗試通過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"))
));

輸出還應包含:

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? 我嘗試了幾種方法,但它不起作用,編譯時出現異常。

請參見如何:控制命名空間前綴 你可以使用這樣的代碼:

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這種方式的含義。

來自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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM