get node value from string xml

foluis picture foluis · May 9, 2013 · Viewed 24.5k times · Source

I have this string XML

string innerXml = @"<detail><WCFFaultExcepcion xmlns=""http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><ErrorId>b7e9d385-9118-4297-baca-db9ab00f3856</ErrorId><Message>Índice fuera de los límites de la matriz.</Message></WCFFaultExcepcion></detail>";

This is the stringXML

<detail>
    <WCFFaultExcepcion xmlns="http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <ErrorId>b7e9d385-9118-4297-baca-db9ab00f3856</ErrorId>
        <Message>Índice fuera de los límites de la matriz.</Message>
    </WCFFaultExcepcion>
</detail>

What I want is to get the value of the detail Tag, I’m trying with this example but all return null o cero count, could you help me?

 private static void Example()
        {
            string innerXml = @"<detail><WCFFaultExcepcion xmlns=""http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><ErrorId>b7e9d385-9118-4297-baca-db9ab00f3856</ErrorId><Message>Índice fuera de los límites de la matriz.</Message></WCFFaultExcepcion></detail>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(innerXml);

            XmlNode node = (XmlNode)doc.DocumentElement;
            XmlNode optionalNode = node.SelectSingleNode("/detail/WCFFaultExcepcion");
            XmlNode optionalNode1 = node.SelectSingleNode("detail/WCFFaultExcepcion");
            XmlNode optionalNode2 = node.SelectSingleNode("/detail/WCFFaultExcepcion/ErrorId");
            XmlNode optionalNode3 = node.SelectSingleNode("detail/WCFFaultExcepcion/ErrorId");
            XmlElement optional = doc.SelectSingleNode(@"/detail/WCFFaultExcepcion/ErrorId") as XmlElement;
            XmlElement optiona2 = doc.SelectSingleNode(@"detail/WCFFaultExcepcion/ErrorId") as XmlElement;
            XmlNode xNode = doc.DocumentElement.SelectNodes("ErrorId")[0];
            XmlNodeList xnList = doc.SelectNodes("/detail/WCFFaultExcepcion");
            XmlNodeList xnList1 = doc.SelectNodes("detail/WCFFaultExcepcion");
            XmlNodeList xnList2 = doc.SelectNodes("/detail/WCFFaultExcepcion/ErrorId");
            XmlNodeList xnList3 = doc.SelectNodes("detail/WCFFaultExcepcion/ErrorId");
        }

Answer

Swen Kooij picture Swen Kooij · May 9, 2013

I think this might be the solution for you:

XmlDocument doc = new XmlDocument();
doc.LoadXml(innerXml);

XmlNodeList ErrorIdTags = doc.GetElementsByTagName("ErrorId");
if(ErrorIdTags.Count <= 1)
{
    // The tag could not be fond
}
else
{
    // The tag could be found!
    string ErrorId = ErrorIdTags[0].InnerText;
}