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

半腔热情 提交于 2019-12-01 03:20:37

问题


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.


回答1:


How about:

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



回答2:


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.




回答3:


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();


来源:https://stackoverflow.com/questions/3100345/how-to-read-processing-instruction-from-an-xml-file-using-net-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!