[ Download Code ]
So how do we access and read an existing processing instruction from an XML document? Processing instructions can be selected just like any other node from a document. The XPath uses a predicate processing-instruction() to test that the node is indeed a processing instruction.
In the System.XML namespace there is a class called XmlProcessingInstruction. When you select a single node from the XML document you can cast the returning XMLNode object to this type which will give you a nice interface to access the processing instruction's value. To read the value, simply select the object's Value member.
To change the value of the processing instruction, simply assign the new string value to the object's Value member.
To add a new processing instruction to the XML document, use the CreateProcessingInstruction method of the XMLDocument class. Then add the XmlProcessingInstruction object to the XML Document by using either the InsertBefore or InsertAfter method.
To delete an existing processing instruction from an XML Document, select the processing instruction node as before, but this time do not cast it to an XMLProcessingInstruction object. Instead keep it as type XmlNode. Then use the RemoveChild method of the XMLDocument class.
Everything is demonstrated in the following code.
// Get physical path of the XML document
string strPath = Server.MapPath("Sample.xml");
// Load the contents of the XML document
XmlDocument doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(strPath);
// display contents of original Sample.xml
txtSample.Text = doc.InnerXml.ToString().Replace("><", ">\r\n\n<");
// read processing instruction from document
XmlProcessingInstruction pi = (XmlProcessingInstruction)doc.SelectSingleNode
("/processing-instruction(\"mso-infoPathSolution\")");
// display processing instruction value
txtMsoInfoPathSolution.Text = pi.Value;
// update processing instruction value
pi.Value = "updated value";
// display updated processing instruction value
txtMsoInfoPathSolutionUpdated.Text = pi.Value;
// create a new processing instruction
XmlProcessingInstruction piNew = doc.CreateProcessingInstruction
("new-pi", "my new processing instruction");
// add processing instruction to the document
doc.InsertBefore(piNew, doc.ChildNodes[3]);
// delete a processing instruction
XmlNode ndDel = doc.SelectSingleNode("/processing-instruction(\"mso-application\")");
doc.RemoveChild(ndDel);
// display in memory changes of Sample.xml to
// show updated and added processing instructions
txtSampleUpdated.Text = doc.InnerXml.ToString().Replace("><", ">\r\n\n<");