开发者

Problem with LINQ to XML and Namespaces

开发者 https://www.devze.com 2022-12-23 05:49 出处:网络
I am having problems with working with a third party XML string that contains a Namespace with LINQ to XML.

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?开发者_如何转开发


Doesn't that compile to the equivalent of (in C# terms):

var el2 = XmlWithNs.Descendants("DATABASEPW").FirstOrDefault();

where-as to get "DATABASEPW" in the right namespace you would need the equivalent of:

XNamespace ns = "http://www.cgi.com/Ratabase";
var el2 = XmlWithNs.Descendants(ns + "DATABASEPW").FirstOrDefault();

Translate to VB and you should be set?

Reflector assures me (but don't quote me!) that this is something like:

Dim ns As XNamespace = "http://www.cgi.com/Ratabase"
Dim el2 As XElement = XmlWithNs.Descendants(ns + "DATABASEPW").FirstOrDefault
0

精彩评论

暂无评论...
验证码 换一张
取 消