我需要在C#中编写一个xml,我希望将文本格式化。 这些是我的设置:
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = ("\t"),
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
XmlWriter xmlWriter = XmlWriter.Create(path + "//" + nome, settings);
在标题和第一个节点之后,我应该插入这个字符串:
string st = "\r\nLINE 1\r\nLINE 2\r\nLINE 3\r\n";
我希望将其格式化如下:
<Text>
LINE 1
LINE 2
LINE 3
</Text>
我写了这段代码:
xmlWriter.WriteString(st);
答案 0 :(得分:0)
要实现此类结果,您应该实现自定义XmlWriter
:
public class IndentTextXmlWriter : XmlTextWriter
{
private int indentLevel;
private bool isInsideAttribute;
public IndentTextXmlWriter(TextWriter textWriter): base(textWriter)
{
}
public bool IndentText { get; set; }
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
isInsideAttribute = true;
base.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
isInsideAttribute = false;
base.WriteEndAttribute();
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
indentLevel++;
base.WriteStartElement(prefix, localName, ns);
}
public override void WriteEndElement()
{
indentLevel--;
base.WriteEndElement();
}
public override void WriteString(string text)
{
if (String.IsNullOrEmpty(text) || isInsideAttribute || Formatting != Formatting.Indented || !IndentText || XmlSpace == XmlSpace.Preserve)
{
base.WriteString(text);
return;
}
string[] lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string indent = new string(IndentChar, indentLevel * Indentation);
foreach (string line in lines)
{
WriteRaw(Environment.NewLine);
WriteRaw(indent);
WriteRaw(line.Trim());
}
WriteRaw(Environment.NewLine);
WriteRaw(new string(IndentChar, (indentLevel - 1) * Indentation));
}
}
你可以像这样使用它:
[TestMethod]
public void WriteIndentedText()
{
var result = new StringBuilder();
using (var writer = new IndentTextXmlWriter(new StringWriter(result)){Formatting = Formatting.Indented, IndentText = true})
{
string text = @" Line 1
Line 2
Line 3 ";
// some root
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteStartElement("child");
// test auto-indenting
writer.WriteStartElement("elementIndented");
writer.WriteString(text);
writer.WriteEndElement();
// test space preserving
writer.WriteStartElement("elementPreserved");
writer.WriteAttributeString("xml", "space", null, "preserve");
writer.WriteString(text);
writer.WriteEndDocument();
}
Debug.WriteLine(result.ToString());
}
输出:
<?xml version="1.0" encoding="utf-16"?>
<root>
<child>
<elementIndented>
Line 1
Line 2
Line 3
</elementIndented>
<elementPreserved xml:space="preserve"> Line 1
Line 2
Line 3 </elementPreserved>
</child>
</root>