类似兄弟的C#XML子节点

时间:2016-07-18 22:18:58

标签: c# xml

我试图修改我们最初没有创建的XML文档。来自XML的Snippit如下:

<DEALS>
  <DEAL>
    <LOANS>
      <LOAN LoanRoleType="SubjectLoan">
        <BUYDOWN>
          <BUYDOWN_RULE>
            <BuydownInformation>0</BuydownInformation>
          </BUYDOWN_RULE>
        </BUYDOWN>
      </LOAN>
      <LOAN LoanRoleType="SubjectLoan">
        <LOAN_IDENTIFIERS>
          <LOAN_IDENTIFIER>
          ...
          </LOAN_IDENTIFIER>
          <LOAN_IDENTIFIER>
            <SellerLoanIdentifier>1234567890</SellerLoanIdentifier>
          </LOAN_IDENTIFIER>
        </LOAN_IDENTIFIERS>
      </LOAN>
    </LOANS>
  </DEAL>
  <DEAL>
    ...Same format as above...
  </DEAL>
</DEALS>

每个LOAN的第一个DEAL元素永远不会包含LOAN_IDENTIFIERS。我需要获取SellerLoanIdentifier的InnerText,然后将其放入第一个<BuydownInformation>元素的LOAN。我尝试过嵌套循环,似乎无法区分两个LOAN元素(第二个循环甚至看不到LOAN元素)。我认为它也可能与这样一个事实有关,即它们都具有完全相同的属性,但到目前为止无法在网上找到任何帮助。

XmlDocument xmlExport = new XmlDocument();
xmlExport.Load(fileDestination);

string loanNumber = "";

XmlNodeList loan_XMLDeals = xmlExport.GetElementsByTagName("DEAL");
Logger.WriteDebug("Found " + loan_XMLDeals.Count + " Deals");
foreach (XmlNode loan_XMLDeal in loan_XMLDeals)
{
    XmlNodeList loan_XMLLoans = loan_XMLDeal.SelectNodes("LOAN");
    Logger.WriteDebug("Found " + loan_XMLLoans.Count + " Loan categories");
    foreach (XmlNode loan_XMLCategory in loan_XMLLoans)
    {
        if(loan_XMLCategory.SelectSingleNode("SellerLoanIdentifier") != null)
        {
            loanNumber = loan_XMLCategory.SelectSingleNode("SellerLoanIdentifier").ToString();
            Logger.WriteDebug("Got loan number " + loanNumber);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个简单的XML Linq代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> loans = doc.Descendants("LOANS").ToList();
            foreach (XElement loan in loans)
            {
                string sellerLoanIdentifier = (string)loan.Descendants("SellerLoanIdentifier").FirstOrDefault();
                XElement buydownInformation = loan.Descendants("BuydownInformation").FirstOrDefault();
                buydownInformation.Value = sellerLoanIdentifier;
            }
        }
    }
}