我需要在 XML 的列表中获取父节点的子节点,以便我可以将它们放在循环中以将所有值放入 Excel 中

本文关键字:循环 Excel 我可以 父节点 获取 列表 子节点 XML | 更新日期: 2023-09-27 18:33:04

我正在发送一个XML字符串作为Web服务,我想解释它。我的 XML 字符串如下所示:

<?xml version="1.0" encoding="utf-8"?>
<result is_array="true">
    <item>
        <candidate_offer_id>175</candidate_offer_id><contact_person>Ranjeet Singh</contact_person><offer_status>8</offer_status>
        </item>
        <item><candidate_offer_id>176</candidate_offer_id><contact_person>Ranjeet Singh</contact_person><offer_status>8</offer_status>
    </item>
</result>

在这个 XML 字符串中,我想访问像 candidate_offer_id 这样的子节点,在列表中的节点 下offer_status名称,以便稍后我可以运行循环以在循环中获取所有这些值并将其放在 Excel 工作表上。到目前为止,我一直这样写:

WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(responseStream);
string responseFromServer = reader.ReadToEnd();
StringBuilder output = new StringBuilder();
var str = XElement.Parse(responseFromServer);
var result = str.Element("item");

但是,如何插入var结果以获取列表中父节点的标记名称以及如何解释它?

我需要在 XML 的列表中获取父节点的子节点,以便我可以将它们放在循环中以将所有值放入 Excel 中

您还可以使用XmlDocument类来加载和操作 XML。

XmlDocument doc = new XmlDocument();
//doc.Load(responseStream); -- Stream loading
doc.LoadXml(responseFromServer); // where responseFromServer is a xml string
XmlNodeList list = doc.DocumentElement.SelectNodes("//item/*");
foreach (XmlNode n in list)
{
    Console.WriteLine("{0} : {1}", n.Name, n.Value);
}
// As a list object that can be converted further
IEnumerable<XmlNode> node = list.Cast<XmlNode>();

我假设<code>标签有错误;如果没有,则 xml 需要更正才能使用。

* 更新:简化了将子节点提取为列表的代码

首先,您的 XML 无效。您希望在<?xml>之后<code>,例如:

<?xml version=""1.0"" encoding=""utf-8""?>
<code>
    <result is_array=""true"">
        <item>
            <candidate_offer_id>175</candidate_offer_id><contact_person>Ranjeet Singh</contact_person><offer_status>8</offer_status>
        </item>
        <item><candidate_offer_id>176</candidate_offer_id><contact_person>Ranjeet Singh</contact_person><offer_status>8</offer_status>
        </item>
    </result>
</code>

我会创建一个类来包含每个项目,例如

static void Main(string[] args)
{
    var str = XElement.Parse(xml);
    var items = str.Descendants("item");
    List<Item> Items = new List<Item>();
    foreach (var item in items)
    {
        Items.Add(new Item
        {
            OfferID = Convert.ToInt32(item.Element("candidate_offer_id").Value),
            Person = item.Element("contact_person").Value,
            Status = Convert.ToInt32(item.Element("offer_status").Value)
        });
    }
}
class Item
{
    public int OfferID { get; set; }
    public string Person { get; set; }
    public int Status { get; set; }
}

XDocument 将适用于这种情况,因为您没有使用整个 XML 结构。

假设您的 XML 有效,例如:

<?xml version="1.0" encoding="UTF-8"?>
<result is_array="true">
    <item>
        <candidate_offer_id>175</candidate_offer_id>
        <contact_person>Ranjeet Singh</contact_person>
        <offer_status>8</offer_status>
    </item>
    <item>
        <candidate_offer_id>176</candidate_offer_id>
        <contact_person>Ranjeet Singh</contact_person>
        <offer_status>8</offer_status>
    </item>
</result>

DTO:

public class CandidateOffer
{
    public int CandidateOfferId { get; set; }
    public string ContactPerson { get; set; }
    public int OfferStatus { get; set; }
}

解析 器:

public CandidateOffer ParseCandidateOffer(XElement element)
{
    int candidateOfferId;
    if(!int.TryParse(element.Element("candidate_offer_id").Value,
                     out candidateOfferId))
    {
        candidateOfferId = 0;
    }
    var contactPerson = element.Element("contact_person").Value;
    int offerStatus;
    if(!int.TryParse(element.Element("offer_status").Value,
                     out offerStatus))
    {
        offerStatus = 0;
    }
    return new CandidateOffer
            {
                CandidateOfferId = candidateOfferId,
                ContactPerson = contactPerson,
                OfferStatus = offerStatus
            };
}

用法:

var xDocument = XDocument.Parse(xmlString);
var candidateOffers = xDocument.XPathSelectElements("//item")
                               .Select(ParseCandidateOffer);
foreach(var candidateOffer in candidateOffers)
{
    Console.WriteLine(candidateOffer.CandidateOfferId);
}