我有一个简短的问题,我想获得Type Value“someType” 来自这样的XML结构:
<?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>
我尝试了更多可能的解决方案,但没有给我类型
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);
}
什么错了?
答案 0 :(得分:2)
正如其他人所说,XDocument是可行的方法。还有一个命名空间,这意味着你需要做这样的事情:
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;