7

How to check whether an Xml file have processing Instruction

Example

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

 <Root>
    <Child/>
 </Root>

I need to read the processing instruction

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

from the XML file.

Please help me to do this.

bluish
  • 26,356
  • 27
  • 122
  • 180
Thorin Oakenshield
  • 14,232
  • 33
  • 106
  • 146

3 Answers3

18

How about:

XmlProcessingInstruction instruction = doc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction;
Garett
  • 16,632
  • 5
  • 55
  • 63
6

You can use FirstChild property of XmlDocument class and XmlProcessingInstruction class:

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 Value or Data properties to get appropriate values.

bluish
  • 26,356
  • 27
  • 122
  • 180
brain_pusher
  • 1,507
  • 3
  • 21
  • 31
0

How about letting the compiler do more of the work for you:

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

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