在XML节点中添加XML值后,缩进就会中断,当前XML节点的所有子节点看起来都很难看,根本不可读,但XML文件仍然有效,我的XML扫描程序工作正常。
Example of using XML-File which has no XML-value in XML-node
Example of using XML-File which has XML-value in XML-node and children
我们走吧!
public class XmlNodeSerializer : INodeSerializer
{
private readonly XmlTextWriter _xmlWriter;
public XmlNodeSerializer(TextWriter writer)
{
if(writer == null)
throw new ArgumentNullException($"{nameof(writer)}");
_xmlWriter = new XmlTextWriter(writer);
_xmlWriter.Formatting = Formatting.Indented;
}
public void Serialize(Node node)
{
if(node == null)
throw new ArgumentNullException($"{nameof(node)}");
using (_xmlWriter)
{
_xmlWriter.WriteStartDocument();
WriteXmlNode(node, _xmlWriter);
_xmlWriter.WriteEndDocument();
}
}
private static void WriteXmlNode(Node target, XmlWriter wr)
{
wr.WriteStartElement(target.Name);
if (target.HasAttributes())
foreach (var attr in target.Attributes)
wr.WriteAttributeString(attr.Key, attr.Value);
if(target.HasValue())
wr.WriteValue(target.Value);
if (target.HasChildren())
foreach (var child in target.Children)
WriteXmlNode(child, wr);
wr.WriteEndElement();
}