How to read processing instructions from an XML file using .NET 3.5

How to check if an Xml file has processing instructions

Example

 <?xml-stylesheet type="text/xsl" href="Sample.xsl"?>

 <Root>
    <Child/>
 </Root>

I need to read the processing instructions

<?xml-stylesheet type="text/xsl" href="Sample.xsl"?>

from an XML file.

Please help me do this.

+4
source share
3 answers

What about:

XmlProcessingInstruction instruction = doc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction;
+16
source

You can use the FirstChildclass property XmlDocumentand XmlProcessingInstructionclass:

XmlDocument doc = new XmlDocument();
doc.Load("example.xml");

if (doc.FirstChild is XmlProcessingInstruction)
{
    XmlProcessingInstruction processInfo = (XmlProcessingInstruction) doc.FirstChild;
    Console.WriteLine(processInfo.Data);
    Console.WriteLine(processInfo.Name);
    Console.WriteLine(processInfo.Target);
    Console.WriteLine(processInfo.Value);
}

Parse Valueor Dataproperties to get the appropriate values.

+5
source

, :

XmlDocument Doc = new XmlDocument();
Doc.Load(openFileDialog1.FileName);

XmlProcessingInstruction StyleReference = 
    Doc.OfType<XmlProcessingInstruction>().Where(x => x.Name == "xml-stylesheet").FirstOrDefault();
0

All Articles