處理指令(Processing Instruction, PI)格式:<?target value?>。用於傳遞特定應用程式資訊,不屬於文件資料一部分,解析器直接透傳給客戶端應用。
value 格式預定義(version="1.0" encoding="utf-8")。<?xml-stylesheet href="style.css" type="text/css"?>,value 為偽屬性字串。<?mso-application progid="InfoPath.Document"?>、<?mso-infoPathSolution ...?> 指定方案模板位置。| 操作 | 方法 |
|---|---|
| 選取 PI 節點 | XPath: /processing-instruction('target') |
| 轉型存取值 | (XmlProcessingInstruction)node).Value |
| 修改值 | pi.Value = "new value" |
| 建立新 PI | doc.CreateProcessingInstruction("target", "value") |
| 插入文件 | doc.InsertBefore/After(pi, refNode) |
| 刪除 PI | doc.RemoveChild(node)(無需轉型) |
string path = "config.xml";
XmlDocument doc = new XmlDocument { XmlResolver = null };
doc.Load(path);
// 顯示原始內容
Console.WriteLine(doc.InnerXml.Replace("><", ">\r\n<"));
// 讀取特定 PI
XmlProcessingInstruction pi = (XmlProcessingInstruction)
doc.SelectSingleNode("/processing-instruction('mso-infoPathSolution')");
Console.WriteLine("原值:" + pi.Value);
// 修改
pi.Value = "updated value";
Console.WriteLine("新值:" + pi.Value);
// 新增 PI
XmlProcessingInstruction piNew = doc.CreateProcessingInstruction("new-pi", "my new processing instruction");
doc.InsertBefore(piNew, doc.ChildNodes[3]);
// 刪除 PI
XmlNode ndDel = doc.SelectSingleNode("/processing-instruction('mso-application')");
doc.RemoveChild(ndDel);
// 顯示修改後
Console.WriteLine(doc.InnerXml.Replace("><", ">\r\n<"));