简体   繁体   中英

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

So I am using C# to create an XML document and using the System.Xml.Linq package.

I have a value I want to set in my xml that contains the character ':'

prefix:myVar

My code looks like this:

node.setAttribute("prefix:myVar", "myVarValue");

Where node is an XElement

I get the following exception when that line gets executed:

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

I am guessing it's because the string prefix:myVar contains the character : . Is there a way around this?

The : is not allowed as part of the name because it's reserved to separate the namespace prefix from the local name. In this context, prefix is a namespace prefix and myVar is the local name.

The prefix is only valid if it is declared in the scope of the element it appears in, and it needs to have an associated namespace - which is omitted in your example, so I'll use http://example.com/ to illustrate:

XNamespace ex = "http://example.com/";

var element = new XElement("foo",
    new XAttribute(XNamespace.Xmlns + "prefix", ex),
    new XAttribute(ex + "myVar", "value"));

Note the name of the attribute is ex + "myVar" . This will create an element like this:

<foo xmlns:prefix="http://example.com/" prefix:myVar="value" />

I've explicitly added the declaration using new XAttribute(XNamespace.Xmlns + "prefix", ex) above, but note this isn't required. If you omit it then one will be generated for you:

XNamespace ex = "http://example.com/";

var element = new XElement("foo",
    new XAttribute(ex + "myVar", "value"));

Will result in this:

<foo p1:myVar="value" xmlns:p1="http://example.com/" />

The two outputs are semantically identical.

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