Problem with LINQ to XML and Namespaces

Posted by abtcabe on Stack Overflow See other posts from Stack Overflow or by abtcabe
Published on 2010-03-12T20:37:52Z Indexed on 2010/03/12 20:47 UTC
Read the original article Hit count: 183

Filed under:
|

I am having problems with working with a third party XML string that contains a Namespace with LINQ to XML.

In the below code everything works find. I am able to select the xElement (xEl1) and update its value.

    'Example Without Namespace
    Dim XmlWithOutNs = _
    <?xml version="1.0"?>
    <RATABASECALC>
        <RATEREQUEST>
            <ANCHOR>
                <DATABASENAME>DatabaseName</DATABASENAME>
                <DATABASEPW>DatabasePw</DATABASEPW>
            </ANCHOR>
        </RATEREQUEST>
    </RATABASECALC>

    Dim xEl1 = XmlWithOutNs...<DATABASEPW>.FirstOrDefault
    If xEl1 IsNot Nothing Then
        xEl1.Value = "test"
    End If

However, in the below code the xElement (xEl2) returns Nothing. The only difference is the Namespace (xmlns="http://www.cgi.com/Ratabase)

    'Example With Namespace
    Dim XmlWithNs = _
    <?xml version="1.0"?>
    <RATABASECALC xmlns="http://www.cgi.com/Ratabase">
        <RATEREQUEST>
            <ANCHOR>
                <DATABASENAME>DatabaseName</DATABASENAME>
                <DATABASEPW>DatabasePw</DATABASEPW>
            </ANCHOR>
        </RATEREQUEST>
    </RATABASECALC>

    Dim xEl2 = XmlWithNs...<DATABASEPW>.FirstOrDefault
    If xEl2 IsNot Nothing Then
        xEl2.Value = "test"
    End If

So my questions are: 1. Why is this happening? 2. How do I resolve this issue?

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about Xml