简体   繁体   English

从xml文件中获取XML值

[英]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结构中获取类型值“someType”,如下所示:

<?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. 正如其他人所说,XDocument是可行的方法。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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