Datatable.WriteXml - How to preserve spaces in ele

2019-07-25 16:27发布

问题:

I've added functionality in my application where a DataTable is converted into XML, like so:

dtResults.WriteXml(fileName);

_x0020_ is being added instead of spaces within the outputted XML document.

Is it possible to generate XML files without the _x0020_ code? i.e. can an XML file be generated using that method or similar, and actually have the spaces preserved?

This is the DataGrid:

This is the resulting 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:

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

<ElementName Attribute1="value" />

The DataTable.WriteXml method tries to write out the XML file in a consistent way so that another DataTable object can later be used to load the XML and get as close to an exact copy of the original as possible. Therefore, it replaces illegal characters with their hex-values so that the illegal characters are not lost in translation.

So, if you want to write it to XML differently, you need to either:

  • Change the name of the column 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 however you desire
  • Output the XML as you do now, but then run an XSLT script on it to fix the formatting


回答2:

I don't think what you're wanting is possible. I don't believe an XML element name can contain a space, just like a variable name cannot contain a space. What is the reason that it needs to be a space?

If there actually needs to be a space (which I think will render the xml useless for parsing), you can simply do a find and replace in the file.

If you're storing it to read back in and display again in a DataTable, I would just rename the columns once I've read the data back in, replacing _x0020_ with spaces.



回答3:

I am also facing the same problem. I am exporting data from an excel file which contains columns with space. So my columns also contains space. So I tried the following manner.

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

This will replace the _x0020_ and generates xml. But you cannot construct the same datatable using this xml. Its a workaround, I thought of adding its as a suggestion. Thank you.