2011-05-23 57 views
2

如何使用類XDocument並將其屬性名稱設置爲接受冒號字符?我收到此錯誤在XML屬性上使用冒號字符時出錯

「該':'字符,十六進制值0x3A,不能包含在名稱中。」

Dim ns As XNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9" 
Dim xi As XNamespace = "http://www.w3.org/2001/XMLSchema-instance" 

Dim sitemapValue As New XDocument(New XDeclaration("1.0", "utf-8", ""), 
New XElement("urlset", New XAttribute("xmls", ns), 
            New XAttribute("xmls:xi", xi))) 

我只是想下面使用的XDocument類下面的頭輸出。

<?xml version="1.0" encoding="UTF-8"?> 
<urlset 
     xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
      http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"> 

回答

1
Dim ns As XNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9" 
Dim xi As XNamespace = "http://www.w3.org/2001/XMLSchema-instance" 

Dim sitemapValue As New XDocument(New XDeclaration("1.0", "utf-8", ""), New XElement("urlset", New XAttribute("xmls", ns), _ 
            New XAttribute(XNamespace.Xmlns + "xi", xi), New XAttribute(xi + "schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"))) 

輸出:

<urlset xmls="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xi="http://www.w3.org/2001/XMLSchema-instance" xi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" /> 

讓我知道這是你問什麼。

3

嘗試(使用VS 2010,否則,你需要增加續行字符)

Dim ns As XNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9" 
Dim xi As XNamespace = "http://www.w3.org/2001/XMLSchema-instance" 

Dim doc As XDocument = New XDocument(
         New XElement(ns + "urlset", 
            New XAttribute(XNamespace.Xmlns + "xsi", xi), 
            New XAttribute(xi + "schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd")))