| 屬性/方法 | 回傳內容 | 包含根元素 | 適用場景 |
|---|---|---|---|
XmlDocument.InnerXml | 根元素內部的 XML 字串 | 否 | 只需子樹內容、拼接到其他 XML |
XmlDocument.OuterXml | 根元素本身及內部的完整 XML | 是 | 完整文件序列化、儲存、傳輸 |
XmlNode.OuterXml | 該節點本身及子樹 | 是 (該節點) | 特定節點序列化 |
string filePath = @"E:\voucher.xml";
// 範例 XML 內容:
//
// - A
// - B
//
var doc = new XmlDocument();
doc.Load(filePath);
// 1. InnerXml - 不含根節點
string inner = doc.InnerXml;
Console.WriteLine("InnerXml:");
Console.WriteLine(inner);
// 輸出:
// - A
// - B
// 2. OuterXml - 含根節點
string outer = doc.OuterXml;
Console.WriteLine("OuterXml:");
Console.WriteLine(outer);
// 輸出:
//
// - A
// - B
//
// 3. 特定節點 OuterXml
XmlNode item1 = doc.SelectSingleNode("//Item[@Id='1']");
Console.WriteLine("Item 1 OuterXml: " + item1.OuterXml);
// - A
var doc = new XmlDocument();
// 1. 載入檔案
doc.Load(@"C:\Data\config.xml");
// 2. 載入字串
doc.LoadXml("Value ");
// 3. 載入 Stream (含網路串流)
using (var stream = File.OpenRead(@"C:\Data\config.xml"))
doc.Load(stream);
// 4. 載入 TextReader
using (var reader = new StringReader(xmlString))
doc.Load(reader);
// 5. 載入 XmlReader (最高效能、可驗證 XSD)
var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema };
settings.Schemas.Add(null, "schema.xsd");
using (var reader = XmlReader.Create(@"C:\Data\config.xml", settings))
doc.Load(reader);
// 存檔
doc.Save(@"C:\Output\config.xml");
// 存入 Stream
using (var fs = File.Create(@"C:\Output\config.xml"))
doc.Save(fs);
// 存入 TextWriter
using (var sw = new StringWriter())
{
doc.Save(sw);
string xml = sw.ToString();
}
// 存入 XmlWriter (可控制縮排、編碼)
var writerSettings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 };
using (var xw = XmlWriter.Create(@"C:\Output\pretty.xml", writerSettings))
doc.Save(xw);
OuterXml 不包含 XML 宣告 (``),若需完整文件請用 Save 寫入檔案/串流。Load 預設保留非顯著空白,LoadXml 同;若需移除可設定 XmlReaderSettings.IgnoreWhitespace = true。XmlDocument 為 DOM 模型,全載入記憶體,>50MB 檔案建議改用 XmlReader 串流處理或 XDocument (LINQ to XML)。InnerXml (無根節點):

OuterXml (含根節點):

原文連結:https://www.bianceng.cn/Programming/csharp/201410/45577.htm