在C#中,将字符串格式化为XML的最佳方法是什么?

时间:2008-10-12 01:27:01

标签: c# xml string formatting string-formatting

我正在使用C#创建一个轻量级编辑器,并希望知道将字符串转换为格式良好的XML字符串的最佳方法。我希望C#库中有一个公共方法,比如“public bool FormatAsXml(string text,out string formattedXmlText)”,但它可能不那么容易,不是吗?

非常具体地说,“SomeMethod”方法必须是什么才能产生下面的输出?

string unformattedXml;
string formattedXml;

unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>"
formattedXml = SomeMethod(unformattedXml);

Console.WriteLine(formattedXml);

输出:

<?xml version="1.0"?>
  <book id="123">
    <author>Lewis, C.S.</author>
    <title>The Four Loves</title>
  </book>

10 个答案:

答案 0 :(得分:71)

string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);

输出:

<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>

Xml声明不是由ToString()输出的,而是由Save()...

输出
  XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
  Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));

输出:

<?xml version="1.0" encoding="utf-8"?>
<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>

答案 1 :(得分:15)

不幸的是,它不像FormatXMLForOutput方法那么容易,这是微软在这里讨论的;)

无论如何,从.NET 2.0开始,推荐的方法是使用XMlWriterSettingsClass设置格式,而不是直接在XmlTextWriter对象上设置属性。 See this MSDN page了解更多详情。它说:

“在.NET Framework 2.0版本中,建议的做法是使用XmlWriter.Create方法和XmlWriterSettings类创建XmlWriter实例。这使您可以充分利用此版本中引入的所有新功能。有关更多信息,请参阅创建XML Writer。“

以下是推荐方法的示例:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = ("    ");
using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
{
    // Write XML data.
    writer.WriteStartElement("book");
    writer.WriteElementString("price", "19.95");
    writer.WriteEndElement();
    writer.Flush();
}

答案 2 :(得分:13)

使用新的System.Xml.Linq命名空间(System.Xml.Linq程序集),您可以使用以下命令:

string theString = "<nodeName>blah</nodeName>";
XDocument doc = XDocument.Parse(theString);

您还可以使用以下内容创建片段:

string theString = "<nodeName>blah</nodeName>";
XElement element = XElement.Parse(theString);

如果字符串还不是XML,您可以这样做:

string theString = "blah";
//creates <nodeName>blah</nodeName>
XElement element = new XElement(XName.Get("nodeName"), theString); 

在最后一个示例中要注意的是XElement将对所提供的字符串进行XML编码。

我强烈推荐新的XLINQ课程。它们重量更轻,并且更容易使用大多数现有的XmlDocument相关类型。

答案 3 :(得分:9)

假设您只是想重新格式化XML文档以将新节点放在新行上并添加缩进,那么,如果您使用的是.NET 3.5或更高版本,则最佳解决方案是使用XDocument解析输出,像是这样的事情:

string unformattedXml;
string formattedXml;

unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
formattedXml = System.Xml.Linq.XDocument.Parse(unformattedXml).ToString();

Console.WriteLine(formattedXml);

Neat hu?

然后应该重新格式化XML节点。

使用以前版本的框架执行此操作需要更多的工作,因为没有内置函数来重新计算空白。

事实上,使用pre-Linq类来实现它将是:

string unformattedXml;
string formattedXml;

unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(unformattedXml);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.Xml.XmlWriter xw = System.Xml.XmlTextWriter.Create(sb, new System.Xml.XmlWriterSettings() { Indent = true });
doc.WriteTo(xw);
xw.Flush();
formattedXml = sb.ToString();
Console.WriteLine(formattedXml);

答案 4 :(得分:5)

听起来您想将XML加载到XmlTextWriter个对象中并设置Formatting and Indentation属性:

writer.Formatting = Formatting.Indented;
writer.Indentation = 1;
writer.IndentChar = '\t';

答案 5 :(得分:4)

杰森的方法是最简单的。这是方法:

private static string FormatXmlString(string xmlString)
{
    System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(xmlString);
    return element.ToString();
}

答案 6 :(得分:1)

如果您只需要转义XML字符,则以下内容可能会有用:

string myText = "This & that > <> &lt;";
myText = System.Security.SecurityElement.Escape(myText);

答案 7 :(得分:1)

在Framework 4.0中, 简单。

var unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
var xdoc = System.Xml.Linq.XDocument.Parse(unformattedXml);
var formattedXml = (xdoc.Declaration != null ? xdoc.Declaration + "\r\n" : "") + xdoc.ToString();
Console.WriteLine(formattedXml);

这会增加所需的缩进,维护Xml声明

<?xml version="1.0"?>
<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>

答案 8 :(得分:0)

字符串是否有效?你的意思是如何将XML字符串转换为XML文档?如果是这样,请执行以下操作:

XmlDocument xml = new XmlDocument();

xml.LoadXml( YourString );

答案 9 :(得分:0)

System.Xml.Linq.XElement.ToString()自动格式化!

XElement formattedXML = new XElement.Parse(unformattedXmlString);
Console.WriteLine(formattedXML.ToString());
相关问题