Search code examples
cakebuild

Retrieving an XML value in Cake build?


Is there a simple way of retrieving an XML value from a file using the Cake build automation system?

I've been poking around the Cake.Common.Xml namespace, but everything seems geared toward modifying (XmlPoke) or transforming (XmlTransformation) XML. The docs on those methods make them appear to be geared toward prepping XML for use in later build steps to consume, so they don't return anything.

Ideally, I would like to just go in to a FilePath object with an XPath query string and get the resulting value.

Specifically, I'm trying to extract values from a Xamarin.Android project's AndroidManifest.xml for use in naming the resulting APK from a Cake.Xamarin call, but it seems like this functionality should be at the Cake.Common.Xml level.


Solution

  • As of Cake v0.8.0, there is now XmlPeek from the Cake.Common.Xml.XmlPeekAliases namespace. You pass it a FilePath instance and an XPath query (with optional settings for things like namespaces), and it will return a string.

    For example, given some local XML file like this…

    <some>
        <nested>
            <thing someattribute="attributevalue" />
            <otherthing>some text value</otherthing>
        </nested>
    </some>
    

    For example, to get an attribute's value…

    var attributeValue = XmlPeek(File("example.xml"),
        "/some/nested/thing/@someattribute")
    

    …will get you a string of attributevalue.

    And to get a text nodes value…

    var textNodeValue = XmlPeek(File("example.xml"),
        "/some/nested/otherthing/text()");
    

    …will get you a string of some text value.