我正在尝试使用字符串数据(这是一个xml)创建一个xml文件。但主要问题是我创建的xml格式不正确。我已经使用XmlWriterSettings来格式化xml,但它似乎不起作用。任何人都可以告诉我这段代码有什么问题。
string unformattedXml = @"<datas><data1>sampledata1</data1><datas>";
XmlWriterSettings xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true};
using (XmlWriter writer = XmlWriter.Create(Console.Out, xmlSettingsWithIndentation))
{
writer.WriteRaw(unformattedXml);
}
实际上,当我在XmlDocument中加载此字符串然后将其保存为文件时,它已被格式化。我只是想知道为什么它不能与XmlWriter一起使用。
非常感谢你的帮助。
由于 亚历克斯。
答案 0 :(得分:1)
忽略空格尝试:
private static string FormatXML(string unformattedXml) {
// first read the xml ignoring whitespace
XmlReaderSettings readeroptions= new XmlReaderSettings {IgnoreWhitespace = true};
XmlReader reader = XmlReader.Create(new StringReader(unformattedXml),readeroptions);
// then write it out with indentation
StringBuilder sb = new StringBuilder();
XmlWriterSettings xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true};
using (XmlWriter writer = XmlWriter.Create(sb, xmlSettingsWithIndentation)) {
writer.WriteNode(reader, true);
}
return sb.ToString();
}
答案 1 :(得分:0)
class Program
{
static void Main(string[] args)
{
string unformattedXml = @"<datas><data1>sampledata1</data1></datas>";
XmlReader rdr = XmlReader.Create(new StringReader(unformattedXml));
StringBuilder sb = new StringBuilder();
XmlWriterSettings xmlSettingsWithIndentation =
new XmlWriterSettings
{
Indent = true
};
using (XmlWriter writer = XmlWriter.Create(sb, xmlSettingsWithIndentation))
{
writer.WriteNode(rdr, true);
}
Console.WriteLine(sb);
Console.ReadKey();
}
}
输出:
<?xml version="1.0" encoding="utf-16"?>
<datas>
<data1>sampledata1</data1>
</datas>
请参阅类似的问题: XmlWriter.WriteRaw indentation XML indenting when injecting an XML string into an XmlWriter