How to read processing instruction from an XML file using .NET 3.5
Asked Answered
S

3

6

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.

Selective answered 23/6, 2010 at 9:12 Comment(1)
there's no such thing as "C# 3.5". You are asking about .NET 3.5.Ozonide
F
17

How about:

XmlProcessingInstruction instruction = doc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction;
Fiducial answered 23/6, 2010 at 18:38 Comment(0)
E
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.

Expeditionary answered 23/6, 2010 at 9:40 Comment(0)
O
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();
Ogdoad answered 23/9, 2016 at 19:13 Comment(1)
Welcome to Stack Overflow! Please edit your answer to explain how does the code in this answer work.Hildredhildreth

© 2022 - 2024 — McMap. All rights reserved.