在XML属性上使用冒号错误

问题描述

| 如何使用XDocument类并将其属性名称设置为接受冒号字符?我得到这个错误   \“名称中不能包含\':\'字符,十六进制值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\">
    

解决方法

尝试(使用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\")))
    ,
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\",\"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\" />
让我知道这是否是您要的。