简体   繁体   中英

Error using colon character on XML attributes

How do I use the class XDocument and set its attribute name to accept colon character? I get this error

"The ':' character, hexadecimal value 0x3A, cannot be included in a name."

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

I simply want the following header output below using the XDocument class.

<?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">

Try (with VS 2010, otherwise you need to add line continuation characters)

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", xi), New XAttribute(xi + "schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd")))

Outputs:

<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" />

Let me know if this is what you were asking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM