如何使用c#从XML中获取特定的XML值
本文关键字:XML 获取 何使用 | 更新日期: 2023-09-27 18:13:03
我将下面的XML设置为:
<Requests xmlResponse="true">
<Request response="yes" responsewait="120000" sequence="1" type="Fulfillment">
<RequestData>
<PrintControl>FTP</PrintControl>
<User>81DF</User>
<Documents>
<AddressChangeLetter>
<DocumentInfo>
<AddressChange AddressChangeId="109346" Branch="418" LastChangeDate="">
<Name>AAA NOVAK</Name>
<TaxID>123123121</TaxID>
<OldAddress1>BOX 216</OldAddress1>
<OldAddress2>NYANE 68017</OldAddress2>
<OldAddress3 />
<OldAddress4 />
<NewAddress1>P O BOX 216</NewAddress1>
<NewAddress2>CERESCO NE 68017</NewAddress2>
<NewAddress3 />
<NewAddress4 />
<DateChanged>05/08/2013</DateChanged>
<AccountInfo AcctNum="231232311" AcctStatusCodes="IX" />
</AddressChange>
</DocumentInfo>
</AddressChangeLetter>
</Documents>
</RequestData>
我想获得标签"Documents"下的名称或值。由于在上面的XML中,"Document"标签下的标签是"AddressChangeLetter",因此,我想获得这个名称。我该怎么做呢?
类似于…(它不是完美的,但它会让你开始-谷歌我用来使它正常工作的功能):
XmlDocument xml = new XmlDocument();
xml.Load(yourPathGoesHere)
XmlNodeList addressNodes = xml.GetElementsByTagName("AddressChange");
foreach (XmlNode oneNode in addressNodes) {
myVariableToGrabNames = oneNode["Name"].InnerText;
}
使用Linq to XML很容易做到这一点,例如
var xml = ...;
var xdoc = XDocument.Parse(xml);
foreach (var e in xdoc.Descendants("Documents").Elements())
{
var name = e.Name; // AddressChangeLetter
}