Search code examples
c#xmlxpathattributesprocessing-instruction

Reading XML attribute from a processing instruction line


I have the following line in a XML document

<?ish ishref="GUID-XXXXXXXXXXXXXXXXXXXX" version="1" lang="ae" srclng="en"?>

and want to read (and modify) the lang attribute. I have tried the following:

newXMLDoc.Load(XMLfile);
instruction = newXMLDoc.SelectSingleNode("/processing-instruction('ish')")
         as XmlProcessingInstruction;

instruction returned a valid object with the innerText equal to "it's" line but I don't know how to access the attributes (tried various ways but all return null)

How do I Access the attributes of instruction (or is there another way of doing the access better) ?

I have tried XPath like "/ish@lang" and instruction.Attributes but those just return NULL.

I would prefer a non LINQ solution, I'm using .NET 4.5


Solution

  • Processing instruction contains just text - the XML specification does not impose any restrictions on the content nor gives any structure to them. So to get the inner text you just use Value property:

    var newXMLDoc = new XmlDocument();
    newXMLDoc.LoadXml("<?ish t='v' u='v'?><R></R>");
    var instruction = newXMLDoc.SelectSingleNode("/processing-instruction('ish')")
                 as XmlProcessingInstruction;
    Console.WriteLine(instruction.Value); // t='v' u='v'
    

    Parsing of resulting value depends on how strict values of the PI are. Simple String.Split on space and than on '=' may be enough if you know that values don't have spaces, otherwise some more intricate method, maybe RegEx would need to be written.

    If format is relatively fixed or you just need to replace something - string.Replace (or RegEx.Replace) could work:

      instruction.Value = instruction.Value.Replace("lang=\"ae\"", "lang=\"XX\"");