43

C# で軽量エディターを作成していますが、文字列を適切にフォーマットされた XML 文字列に変換するための最良の方法を知りたいです。「public bool FormatAsXml(string text, out stringformattedXmlText)」のようなパブリック メソッドが C# ライブラリにあることを願っていますが、それほど簡単ではありません。

非常に具体的には、以下の出力を生成するメソッド「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>
4

10 に答える 10

74
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-12T23:01:07.243 に答える
15

残念ながら、いいえ、それはFormatXMLForOutputメソッドほど簡単ではありません。これはMicrosoftがここで話していたものです;)

とにかく、.NET 2.0以降、推奨されるアプローチは、XmlTextWriterオブジェクトに直接プロパティを設定するのではなく、XMlWriterSettingsClassを使用してフォーマットを設定することです。 詳細については、このMSDNページを参照してください。それは言う:

「.NETFrameworkバージョン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();
}
于 2008-10-12T02:24:37.427 に答える
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関連のタイプのほとんどよりも使いやすくなっています。

于 2008-10-12T03:33:44.900 に答える
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);

ニート?

これにより、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);
于 2010-08-13T08:09:41.470 に答える
5

XML をXmlTextWriterオブジェクトにロードし、Formatting プロパティと Indentation プロパティを設定する必要があるようです。

writer.Formatting = Formatting.Indented;
writer.Indentation = 1;
writer.IndentChar = '\t';
于 2008-10-12T01:41:25.300 に答える
4

ジェイソンのアプローチは最も単純です。メソッドは次のとおりです。

private static string FormatXmlString(string xmlString)
{
    System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(xmlString);
    return element.ToString();
}
于 2008-10-13T04:45:19.670 に答える
1

XML文字をエスケープする必要がある場合は、次のことが役立つ場合があります。

string myText = "This & that > <> &lt;";
myText = System.Security.SecurityElement.Escape(myText);
于 2008-10-12T04:04:54.400 に答える
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 Declaration が維持されます。

<?xml version="1.0"?>
<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>
于 2013-04-24T06:25:20.240 に答える
0

文字列は有効な XML ですか? XML 文字列を XML ドキュメントに変換する方法を教えてください。その場合は、次のようにします。

XmlDocument xml = new XmlDocument();

xml.LoadXml( YourString );
于 2008-10-12T01:34:00.743 に答える
0

System.Xml.Linq.XElement.ToString() は自動的にフォーマットします!

XElement formattedXML = new XElement.Parse(unformattedXmlString);
Console.WriteLine(formattedXML.ToString());
于 2012-07-10T20:28:04.910 に答える