我正在用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>
发布于 2008-10-12 23:01:07
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>
发布于 2008-10-12 02:24:37
不幸的是,不,它不像FormatXMLForOutput方法那么简单,这就是微软在这里谈论的;)
无论如何,从.NET 2.0开始,推荐的方法是使用XMlWriterSettingsClass设置格式,而不是直接在XmlTextWriter对象上设置属性。See this MSDN page获取更多详细信息。上面写着:
“在XMLFramework2.0版中,建议的做法是使用XmlWriter.Create方法和XmlWriterSettings类创建XmlWriter实例。这使您可以充分利用此版本中引入的所有新功能。有关详细信息,请参阅创建XmlWriterSettings编写器。”
以下是推荐方法的示例:
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();
}
发布于 2008-10-12 03:33:45
使用新的程序集命名空间(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相关类型。
https://stackoverflow.com/questions/194944
复制相似问题