gpt4 book ai didi

c# - 从 xml 文件中获取 XML 值

转载 作者:数据小太阳 更新时间:2023-10-29 02:34:28 31 4
gpt4 key购买 nike

我有一个简短的问题,我想获得类型值“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);
}

怎么了?

最佳答案

正如其他人所建议的那样,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;

关于c# - 从 xml 文件中获取 XML 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32229433/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com