在C#中添加XML属性之前添加空格

时间:2018-06-27 02:00:55

标签: c# xml attributes whitespace

我正在用C#创建XML。但是,在属性值之前添加空格时遇到了困难。

            XmlWriterSettings SettingWritterXML = new XmlWriterSettings();
            SettingWritterXML.Indent = true;
            SettingWritterXML.ConformanceLevel = ConformanceLevel.Document;
            SettingWritterXML.NewLineOnAttributes = false;

            XmlWriter objXmlWriter = XmlWriter.Create(@output_file_path + path + ".xml", SettingWritterXML);
            objXmlWriter.WriteStartDocument();

            objXmlWriter.WriteStartElement("Bin");
            objXmlWriter.WriteString(Environment.NewLine);
            objXmlWriter.WriteStartElement("Bin");
            objXmlWriter.WriteAttributeString("BinCode", "001");
            objXmlWriter.WriteAttributeString("BinCount", tot_pass.ToString());
            objXmlWriter.WriteAttributeString("BinQuality", "Pass");
            objXmlWriter.WriteEndElement();
            objXmlWriter.WriteString(Environment.NewLine);
            objXmlWriter.WriteStartElement("Bin");
            objXmlWriter.WriteAttributeString("BinCode", "040");
            objXmlWriter.WriteAttributeString("BinCount", tot_fail.ToString());
            objXmlWriter.WriteAttributeString("BinQuality", "Fail");
            objXmlWriter.WriteEndElement();
            objXmlWriter.WriteString(Environment.NewLine);
            objXmlWriter.WriteStartElement("Bin");
            objXmlWriter.WriteAttributeString("BinCode", "099");
            objXmlWriter.WriteAttributeString("BinCount", tot_skip.ToString());
            objXmlWriter.WriteAttributeString("BinQuality", "Null");
            objXmlWriter.WriteEndElement();
            objXmlWriter.WriteString(Environment.NewLine);
            objXmlWriter.WriteEndElement();
            objXmlWriter.WriteString(Environment.NewLine);

实际结果:

<?xml version="1.0" encoding="utf-8"?>
<Bin>
<Bin BinCode="001" BinCount="1465" BinQuality="Pass" />
<Bin BinCode="040" BinCount="1231" BinQuality="Fail" />
<Bin BinCode="099" BinCount="113" BinQuality="Null" />
</Bin>

预期结果:

<?xml version="1.0" encoding="utf-8"?>
<Bin>
<Bin BinCode= "001" BinCount= "1465" BinQuality= "Pass" />
<Bin BinCode= "040" BinCount= "1231" BinQuality= "Fail" />
<Bin BinCode= "099" BinCount= "113" BinQuality= "Null" />
</Bin>    

*在属性中“ =”后的空白处。

1 个答案:

答案 0 :(得分:0)

您担心的是没有区别的区别:

  • XML解析器不会在=与{ 属性值。
  • XML序列化程序通常不会公开该级别的控制。
  • 按惯例,没人会在其中添加空格。