White space in XmlElement in C # .Net

XmlElement child = doc.CreateElement(element);

Where doc is the XmlDocument object. When the code executes the above line with element=Tom and Jerry , I get the following error:

The ' ' character, hexadecimal value 0x20, cannot be included in a name.

What should I do to enable ' ' in an XmlDocument? I cannot replace it with anything else.

What are the other characters that the XML element does not support for name ?

+4
source share
3 answers

I assume that you need an element with the value "Tom and Jerry", and that's fine.

It is part of the XML syntax that you cannot have a space in the name of an element or attribute.

Possible method:

 XmlElement child = doc.CreateElement("cartoon"); child.InnerText = "Tom and Jerry"; 

which produces

 <cartoon>Tom and Jerry</cartoon> 

Also, check out XDocument when you can. Much easier than XmlDocument.

 XElement child = new XElement("cartoon", "Tom and Jerry"); 
+6
source

It seems your XML name contains spaces ...

It's illegal:

 <tom and jerry>hi</tom and jerry> 

Must be:

 <tomandjerry>hi</tomandjerry> 
+4
source

U can do the element as follows:

 <element name='Tom and Jerry' /> 

But if you need to save some data for this cartoon and access it by the name of the cartoon:

 <element name='Tom and Jerry'>some data</element> 
0
source

Source: https://habr.com/ru/post/1382486/


All Articles