Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get XML value from xml file

Tags:

c#

xml

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 ?

like image 939
kb_ Avatar asked Sep 26 '26 16:09

kb_


1 Answers

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;
like image 194
Kvam Avatar answered Sep 29 '26 15:09

Kvam