LoadXml添加额外的空格

时间:2013-05-23 03:54:11

标签: c# xml xml-parsing

这就是我的字符串外观

<?xml version="1.0" encoding="UTF-8"?>
<payment id="123456" date="2013-05-16 11:24:59.0">
  <refund id="1" amount="10000.0" reason="refund 1"/>
  <refund id="2" amount="1200.0" reason="refund 2"/>
  <refund id="3" amount="2252.0" reason="refund 3"/>
</payment>

使用以下代码将其转换为xml后:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myString);

我的xml文档如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<payment id="123456" date="2013-05-16 11:24:59.0">
  <refund id="1" amount="10000.0" reason="refund 1" />
  <refund id="2" amount="1200.0" reason="refund 2" />
  <refund id="3" amount="2252.0" reason="refund 3" />
</payment>

注意区别?出于某种原因,所有“退款”元素在结束标记之前都有一个额外的空格。有人知道它为什么会发生吗?我试图将PreserveWhitespace设置为false但它没有帮助。

2 个答案:

答案 0 :(得分:0)

您的XmlDoument将您的XML内容转换为有效标记。意思是,应该在那里是一个空格(它不是必须的,但它是标准)。

您可以尝试将整个XML分为1行,而我星期五的结果将与此处相同。

答案 1 :(得分:0)

This is because of the inline closing of the XML tag.

    <?xml version="1.0" encoding="UTF-8"?>
    <payment id="123456" date="2013-05-16 11:24:59.0"**>**
      <refund id="1" amount="10000.0" reason="refund 1"**/>**
      <refund id="2" amount="1200.0" reason="refund 2"/>
      <refund id="3" amount="2252.0" reason="refund 3"/>
    </payment>

付款在结尾处有单独的结束标记,但退款是自动关闭元素。默认情况下,将在结束标记之前添加空格。如果你不想要间距那么你必须像旧方式那样做

<?xml version="1.0" encoding="UTF-8"?>
        <payment id="123456" date="2013-05-16 11:24:59.0">
          <refund id="1" amount="10000.0" reason="refund 1">**</refund>**
          <refund id="2" amount="1200.0" reason="refund 2"></refund>
          <refund id="3" amount="2252.0" reason="refund 3"></refund>
        </payment>