Alex Rivera | Logout

How can I get the href attribute value out of an <?xml-stylesheet> node?

Asked 2010-01-22T19:00:24.547
9

We are getting an XML document from a vendor that we need to perform an XSL transform on using their stylesheet so that we can convert the resulting HTML to a PDF. The actual stylesheet is referenced in an href attribute of the ?xml-stylesheet definition in the XML document. Is there any way that I can get that URL out using C#? I don't trust the vendor not to change the URL and obviously don't want to hardcode it.

The start of the XML file with the full ?xml-stylesheet element looks like this:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="http://www.fakeurl.com/StyleSheet.xsl"?>
Edit
Report

1 Answer

2

To find the value using a proper XML parser you could write something like this:


using(var xr = XmlReader.Create(input))
{
    while(xr.Read())
    {
        if(xr.NodeType == XmlNodeType.ProcessingInstruction && xr.Name == "xml-stylesheet")
        {
            string s = xr.Value;
            int i = s.IndexOf("href=\"") + 6;
            s = s.Substring(i, s.IndexOf('\"', i) - i);
            Console.WriteLine(s);
            break;
        }
    }
}
answered 2010-01-22T19:29:23.583

Your Answer