空字符串序列化

时间:2010-09-06 06:29:40

标签: c# xml serialization

我正在使用以下代码序列化xml字符串

   StringReader newStringReader = new StringReader(value.Value);
            try
            {
               using (var reader = XmlReader.Create(newStringReader))
               {
                  newStringReader = null;
                  writer.WriteNode(reader, false);
               }
            }
            finally
            {
               if (newStringReader != null)
                  newStringReader.Dispose();
            }

但在我写的xml文件中

  <property i:type="string">
   <name>Test</name>
    <value>
    </value>
 </property>

但是正确的是

 <property i:type="string">
   <name>Test</name>
   <value></value>
 </property>

因为“value”属性是一个空字符串。序列化的方式不是它返回“\ r \ n”。

编剧:

XmlTextWriter writer = new XmlTextWriter(output); 
try { writer.Formatting = System.Xml.Formatting.Indented; 
writer.Indentation = 2; // Konfiguration sichern 
WriteConfiguration(config, writer); 
} 
finally { writer.Close(); }

我做错了什么?

更新 我写了一个xml配置文件。值可以是int,bools等,也可以是其他xml字符串。这些xml字符串使用上面的代码编写。它的工作正常,除了xml字符串中的emtpy字符串元素。

更新2: 如果我手动更改我想写的xml字符串,它可以工作。我替换所有

<tag></tag>

通过

<tag/>

不幸的是,使用正则表达式修改字符串并不是一个“正确”的解决方案。

5 个答案:

答案 0 :(得分:1)

当我将它们作为XDocument类型使用并简单地使用Save方法时,我总是对XML文档的格式化有了更好的运气。例如xmlDoc.Save(“C:\ temp \ xmlDoc.xml”);就那么简单。另外,你可以在整个编辑过程中一遍又一遍地保存,但性能很小(至少没有我注意到的)。

答案 1 :(得分:1)

我想说这是由缩进参数引起的。您是否尝试将Indented属性设置为false?

答案 2 :(得分:0)

我正在编写带有设置的xml文件。在这个文件中也可以是其他xml文件。上面的代码确保它不是用&gt;单行编写的。等,但作为xml中的xml。所以我必须使用WriteNode-Method。

答案 3 :(得分:0)

尝试删除

writer.Formatting = System.Xml.Formatting.Indented; 
writer.Indentation = 2; 

行,看看会发生什么。

答案 4 :(得分:0)

我们通过使用表格的短标签确实克服了这个问题......

<value />

......而不是......

<value></value>

...然后你不能在XML输出中有换行符。为此,您必须在将树传递给编写器之前查询它。

/// <summary>
/// Prepares the XML Tree, to write short format tags, instead
/// of an opening and a closing tag. This leads to shorter and
/// particularly to valid XML files.
/// </summary>
protected static void Sto_XmlShortTags(XmlNode node)
{
  // if there are children, make a recursive call
  if (node.ChildNodes.Count > 0)
  {
    foreach (XmlNode childNode in node.ChildNodes)
      Sto_XmlShortTags(childNode);
  }
  // if the node has no children, use the short format
  else
  {
    if (node is XmlElement)
      ((XmlElement)node).IsEmpty = true;
  }
}
相关问题