简体   繁体   中英

Get XML value from xml file

I have a short question, i would like to get the Type Value "someType" from a XML Structure like this:

<?xml version="1.0" encoding="utf-8"?>
<UniversalInterchange xmlns="http://www.cargowise.com/Schemas/Universal/2011/11" version="1.1">
    <Header>
    </Header>
    <Body>
        <UniversalShipment xmlns="http://www.cargowise.com/Schemas/Universal/2011/11" version="1.1">
            <Shipment>
                <DataContext>
                    <DataTargetCollection>
                        <DataTarget>
                            <Type>someType</Type>
                        </DataTarget>
                    </DataTargetCollection>
                </DataContext>
                <FileType>
                  <SecondType>not this type</SecondType>
                </FileType>
      </Shipment>
     </UniversalShipment>
    </Body>
</UniversalInterchange>

I have tryed it with more possible solutions but nothing gives me the type

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); 

XmlNodeList xnList = xml.SelectNodes("/UniversalInterchange/Body/UniversalShipment/Shipment/DataContext/DataTargetCollection/DataTarget");

foreach (XmlNode xn in xnList)
{
   string type = xn["Type"].InnerText;
   Console.WriteLine("Name: {0} {1}", type);
}

Whats wrong ?

As others have suggested, XDocument is the way to go. There's also a namespace involved, meaning you need to do something like this:

var xDoc = XDocument.Parse(xmlString);

XNamespace ns = "http://www.cargowise.com/Schemas/Universal/2011/11";

var value = xDoc
    .Element(ns + "UniversalInterchange")
    .Element(ns + "Body")
    .Element(ns + "UniversalShipment")
    .Element(ns + "Shipment")
    .Element(ns + "DataContext")
    .Element(ns + "DataTargetCollection")
    .Element(ns + "DataTarget")
    .Element(ns + "Type")
    .Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM