Search code examples
c#xmldocument

get node value from string xml


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");
        }

Solution

  • I think this might be the solution for you:

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(innerXml);
    XmlNodeList errorIdTags = doc.GetElementsByTagName("ErrorId");
    if(errorIdTags.Count == 0)
    {
        // The tag could not be fond
    }
    else
    {
        // The tag could be found!
        string errorId = errorIdTags[0].InnerText;
    }