XML到LINQ解析带有C#名称空间的XML

时间:2014-09-25 20:36:01

标签: c# xml linq

我有以下XML:

<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
    <env:Header/>
    <env:Body>
        <DigSales xmlns="urn:nike:sale:DigitalSalesToSabrix" xmlns:ns2="http://xmlns.int.nike.com/WSFault" FileTime="2014-09-19T23:16:21Z">
            <Tran OrderType="STANDARD" OperatorID="" IsComplimentary="false" ConsumerID="1260046" Currency="USD" InvoiceNo="17779214" BillDate="2014-09-19" BillTime="2014-09-19T22:23:14Z" OrderDate="2014-09-18T20:50:01Z" TranDate="2014-09-19T22:23:14Z" OrderNo="O917950017" StoreNo="150" TranNo="17779214" IsTaxExempt="false">
                <Item isTaxExempt="false" IsTaxInvoiceStatus="true" TaxDate="2014-09-18T13:49:56" IsShipSend="true" Style="SX4801" Commodity_CD="531024" Desc="Nike Hyper Elite Crew Basketball Socks" ActValue="36.00" ID="00884498939512" InvSource="BRD" NormValue="36.00" Qty="2" Type="2001" isNotOnFile="false">
                    <Tax IsManualOverride="false" TaxAmt="3.15"/>
                    <ShipTo Country="US" GeoCode="8382" PostalCode="94102" State="CA" City="SFO" District="" Address2="" Address1="P.O. Box 15687"/>
                    <ShipFrom ShipFromNode="BRD" Country="US" GeoCode="7533" PostalCode="38118" State="TN" City="Memphis" Address2="" Address1="4775 TUGGLE RD DOOR 54"/>
                </Item>
                <Item isTaxExempt="false" IsTaxInvoiceStatus="true" TaxDate="2014-09-18T13:49:56" IsShipSend="false" Style="" Commodity_CD="7812" Desc="Shipping" ActValue="8.00" ID="00000000000100" NormValue="8.00" Qty="1" Type="2002" isNotOnFile="false">
                    <Tax IsManualOverride="false" TaxAmt="0.70"/>
                    <ShipTo Country="US" GeoCode="8382" PostalCode="94102" State="CA" City="SFO" District="" Address2="" Address1="P.O. Box 15687"/>
                    <ShipFrom ShipFromNode="150" Country="US" GeoCode="7533" PostalCode="38118" State="TN" City="Memphis" Address2="" Address1="4775 TUGGLE RD DOOR 54"/>
                </Item>
                <ContactInfo LastName="PO Box" FirstName="Test"/>
            </Tran>
        </DigSales>
    </env:Body>
</env:Envelope>

我无法解析&#34; Tran&#34;。我为解析编写了以下内容:

var body = xdoc.Descendants(XNamespace.Get("http://schemas.xmlsoap.org/soap/envelope/") + "Body").Single();

            var nmspc = XNamespace.Get("http://schemas.xmlsoap.org/soap/envelope/");

            var tran = from trans in xdoc.Element(nmspc + "Body").Elements("DigSales")
                       select trans.Elements("DigSales").Elements("Tran").ToList();

请帮忙。

1 个答案:

答案 0 :(得分:1)

这将使你成为&#34; Tran&#34;的IEnumberable。元素:

var nmspc = XNamespace.Get(@"http://schemas.xmlsoap.org/soap/envelope/");
var ns2 = XNamespace.Get(@"urn:nike:sale:DigitalSalesToSabrix");

var trans = xdoc.Root.Elements(nmspc + "Body").Elements(ns2 + "DigSales").Elements(ns2 + "Tran");