C# XMl缩进未按预期工作!!
我正在尝试使用字符串数据(即xml)创建一个xml文件。但主要问题是我创建的xml格式不正确。我已经使用XmlWriterSettings来格式化xml,但它似乎不起作用。谁能告诉我这个代码有什么问题吗C# XMl缩进未按预期工作!!,c#,xml,C#,Xml,我正在尝试使用字符串数据(即xml)创建一个xml文件。但主要问题是我创建的xml格式不正确。我已经使用XmlWriterSettings来格式化xml,但它似乎不起作用。谁能告诉我这个代码有什么问题吗 string unformattedXml = @"<datas><data1>sampledata1</data1><datas>"; XmlWriterSettings xmlSettingsWithInd
string unformattedXml = @"<datas><data1>sampledata1</data1><datas>";
XmlWriterSettings xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true};
using (XmlWriter writer = XmlWriter.Create(Console.Out, xmlSettingsWithIndentation))
{
writer.WriteRaw(unformattedXml);
}
string unformatedxml=@“sampledata1”;
XmlWriterSettings XmlSettingsWithindention=新XmlWriterSettings{Indent=true};
使用(XmlWriter=XmlWriter.Create(Console.Out,xmlSettingsWithIndentation))
{
writer.WriteRaw(未格式化dxml);
}
实际上,当我将这个字符串加载到XmlDocument中并将其保存为文件时,它被格式化了。我只是想知道它为什么不能与XmlWriter一起工作
你的帮助将不胜感激
谢谢
Alex.如果您使用
XmlReader
而不是原始字符串,它应该可以工作
(当最后一个XML元素不是closed属性时,我认为这是一个输入错误,通过格式化,您可以引用正确的缩进):
类程序
{
静态void Main(字符串[]参数)
{
字符串unformatedxml=@“sampledata1”;
var rdr=XmlReader.Create(新的StringReader(unformatedxml));
var sb=新的StringBuilder();
var xmlSettingsWithIndentation=新的XmlWriterSettings
{
缩进=真
};
使用(var writer=XmlWriter.Create(sb,xmlSettingsWithIndentation))
WriteNode(rdr,true);
(某人);
Console.ReadKey();
}
}
它输出:
<?xml version="1.0" encoding="utf-16"?>
<datas>
<data1>sampledata1</data1>
</datas>
样本数据1
请参阅类似问题:要忽略空白,请尝试以下操作:
private static string FormatXml(string unformattedXml)
{
//First read the xml, ignoring whitespace.
var readeroptions = new XmlReaderSettings { IgnoreWhitespace = true };
var reader = XmlReader.Create(new StringReader(unformattedXml), readeroptions);
//Then write it out with indentation.
var sb = new StringBuilder();
var xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true };
using (var writer = XmlWriter.Create(sb, xmlSettingsWithIndentation))
writer.WriteNode(reader, true);
return sb.ToString();
}
我认为
Indent=true
不适用于WriteRaw
private static string FormatXml(string unformattedXml)
{
//First read the xml, ignoring whitespace.
var readeroptions = new XmlReaderSettings { IgnoreWhitespace = true };
var reader = XmlReader.Create(new StringReader(unformattedXml), readeroptions);
//Then write it out with indentation.
var sb = new StringBuilder();
var xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true };
using (var writer = XmlWriter.Create(sb, xmlSettingsWithIndentation))
writer.WriteNode(reader, true);
return sb.ToString();
}