Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a processing instruction from XML string using C# .NET?

Tags:

c#

parsing

xml

I would like to read a processing instruction from some small well-formed XML chunk, based on this post: How to read processing instruction from an XML file using .NET 3.5

However, it doesn't work. I get the error, that the pi object is null. This is what I do:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<root>Text <?pi 1?>blabla</root>");
Console.WriteLine(doc.ChildNodes[0].Name); // output: root

XmlProcessingInstruction pi = doc.OfType<XmlProcessingInstruction>().Where(x => x.Name == "pi").FirstOrDefault();
Console.WriteLine(pi.Value);

Parsing the XML works. When I get the error (System-NullReferenceException) in Visual Studio, I get it for line "Console.WriteLine(pi.Value);".

Where the error? How do I get/read the processing instruction?

like image 814
capfan Avatar asked Jun 12 '26 19:06

capfan


1 Answers

You have two issues in your code.

The first is that it fails on Console.WriteLine(doc.ChildNodes[1].Name);, "root" is the first node, not the second (zero-based). But this is probably a typo.

As to the issue in question:

Enumerable.OfType() is using GetEnumerator() of XmlDocument class which is implemented by it's parent XmlNode.GetEnumerator(). The documentation states:

An IEnumerator object that can be used to iterate through the child nodes in the current node.

But you are trying to run OfType on doc, who has only a single child: root.

If you change your code to run on root's children instead, it will work as expected:

XmlProcessingInstruction pi = doc.ChildNodes[0].OfType<XmlProcessingInstruction>().Where(x => x.Name == "pi").FirstOrDefault();
like image 111
xCliede Avatar answered Jun 15 '26 11:06

xCliede



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!