Datatable.WriteXml - How to keep spaces in element names

I added functionality to my application where the DataTable converted to XML , for example:

 dtResults.WriteXml(fileName); 

_x0020_ added instead of spaces in the output XML document.

Is it possible to generate XML files without the _x0020_ code? that is, can an XML file be generated using this method or similar and actually save spaces?

This is a DataGrid:

enter image description here

This is the result of XML:

 <Customers> <Customer_x0020_Name>Sean</Customer_x0020_Name> </Customers> <Customers> <Customer_x0020_Name>John</Customer_x0020_Name> </Customers> <Customers> <Customer_x0020_Name>Sarah</Customer_x0020_Name> </Customers> <Customers> <Customer_x0020_Name>Mark</Customer_x0020_Name> </Customers> <Customers> <Customer_x0020_Name>Norman</Customer_x0020_Name> </Customers> 
+1
source share
3 answers

The column name contains a space. XML element names cannot contain a space. The space is used in XML to separate element names from attribute names, for example:

 <ElementName Attribute1="value" /> 

The DataTable.WriteXml method tries to write an XML file in a consistent way, so that later it can use another DataTable to load XML and bring it as close as possible to an exact copy of the original. Therefore, it replaces illegal characters with hexadecimal values, so that illegal characters are not lost during translation.

So, if you want to write it in XML in different ways, you need to either:

  • Change the column name in the DataTable so that it does not contain a space
  • Manually output the XML yourself using XDocument , XmlDocument , XmlWriter or XmlSerializer and format the output, but you want to
  • Output the XML as it is now, and then run the XSLT script to fix the formatting
+6
source

I do not think that what you want is possible. I do not believe that an XML element name can contain a space, just as a variable name cannot contain a space. What is the reason that it should be space?

If there really should be space (which I think would make xml useless for parsing), you can just find and replace in the file.

If you save it for reading and displaying again in a DataTable, I would just rename the columns as soon as I read the data, replacing _x0020_ spaces.

+2
source

I am also facing the same problem. I am exporting data from an excel file that contains columns with a space. Therefore, my columns also contain a space. So I tried the following.

 StringWriter strXML = new StringWriter(); dtPartOriginalData.WriteXml(strXML, XmlWriteMode.IgnoreSchema, false); strMessages = strXML.ToString().Replace("_x0020_", ""); 

This will replace _x0020_ and create xml. But you cannot create the same data type using this xml. The workaround I thought was to add it as a suggestion. Thanks.

0
source

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


All Articles