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

发布于 2024-07-07 07:12:59 字数 708 浏览 6 评论 0原文

我正在用 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>

I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?

Very specifically, what would the method "SomeMethod" have to be that would produce the output below?

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);

Output:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

狼性发作 2024-07-14 07:12:59
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>
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);

Output:

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

The Xml Declaration isn't output by ToString(), but it is by Save() ...

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

Output:

<?xml version="1.0" encoding="utf-8"?>
<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>
壹場煙雨 2024-07-14 07:12:59

不幸的是,它不像 FormatXMLForOutput 方法那么简单,这是 Microsoft 在这里讨论的;)

无论如何,从 .NET 2.0 开始,推荐的方法是使用 XMlWriterSettingsClass 来设置格式,而不是直接在XmlTextWriter 对象。 请参阅此 MSDN 页面了解更多详细信息。 它说:

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

以下是推荐方法的示例:

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();
}

Unfortunately no, it's not as easy as a FormatXMLForOutput method, this is Microsoft were talking about here ;)

Anyway, as of .NET 2.0, the recommended approach is to use the XMlWriterSettingsClass to set up formatting, as opposed to setting properties directly on the XmlTextWriter object. See this MSDN page for more details. It says:

"In the .NET Framework version 2.0 release, the recommended practice is to create XmlWriter instances using the XmlWriter.Create method and the XmlWriterSettings class. This allows you to take full advantage of all the new features introduced in this release. For more information, see Creating XML Writers. "

Here is an example of the recommended approach:

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();
}
微暖i 2024-07-14 07:12:59

使用新的 System.Xml.Linq 命名空间 (System.Xml.Linq Assembly),您可以使用以下内容:

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 相关类型相比,它们的重量更轻,并且更易于使用。

Using the new System.Xml.Linq namespace (System.Xml.Linq Assembly) you can use the following:

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

You can also create a fragment with:

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

If the string is not yet XML, you can do something like this:

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

Something to note in this last example is that XElement will XML Encode the provided string.

I highly recommend the new XLINQ classes. They are lighter weight, and easier to user that most of the existing XmlDocument-related types.

清浅ˋ旧时光 2024-07-14 07:12:59

假设您只是想重新格式化 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);

整齐胡?

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

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

事实上,使用 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);

Assuming your're simply wanting to re-format an XML document to put new nodes on new lines and add indenting, then, if you are using .NET 3.5 or above then the best solution is to parse then output with XDocument, somthing like:

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?

This should then re-format the XML nodes.

To do this with previous versions of the framework requires a lot more legwork as there is no built in functions to re-calculate the whitespace.

In fact, to do it using pre-Linq classes would be:

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);
尸血腥色 2024-07-14 07:12:59

听起来您想将 XML 加载到 XmlTextWriter 对象并设置格式和缩进属性:

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

It sounds like you want to load the XML into an XmlTextWriter objects and set the Formatting and Indentation properties:

writer.Formatting = Formatting.Indented;
writer.Indentation = 1;
writer.IndentChar = '\t';
叫嚣ゝ 2024-07-14 07:12:59

Jason 的方法是最简单的。 方法如下:

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

Jason's approach is the simplest. Here's the method:

private static string FormatXmlString(string xmlString)
{
    System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(xmlString);
    return element.ToString();
}
半﹌身腐败 2024-07-14 07:12:59

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

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

If you just need to escape XML characters the following might be useful:

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

在 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>

In Framework 4.0 it is simple.

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);

This adds in the required indentation, and maintains the Xml Declaration.

<?xml version="1.0"?>
<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>
好久不见√ 2024-07-14 07:12:59

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

XmlDocument xml = new XmlDocument();

xml.LoadXml( YourString );

Is the string valid XML? Do you mean how can you convert an XML string into an XML document? If so, do this:

XmlDocument xml = new XmlDocument();

xml.LoadXml( YourString );
谁对谁错谁最难过 2024-07-14 07:12:59

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

XElement formattedXML = new XElement.Parse(unformattedXmlString);
Console.WriteLine(formattedXML.ToString());

System.Xml.Linq.XElement.ToString() Automatically Formats!

XElement formattedXML = new XElement.Parse(unformattedXmlString);
Console.WriteLine(formattedXML.ToString());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文