我从调用Zoho Crm api获得了这个xml:https://ix-infiniti-preview.azurewebsites.net/Manage/zohotest.xml
我想循环遍历此xml的每一行,并为每行创建一个DataTable行数据。这就是我想出的:
//Get List of fields
List<string> fields = data.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToList();
List<MalformedLineException> exceptions = new List<MalformedLineException>();
List<string> values = new List<string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlData);
// Count number of row returned
XmlNodeList xmlNL = xmlDoc.GetElementsByTagName("row");
int rowCount = xmlNL.Count;
for (int row = 1; row <= rowCount; row++)
{
DataRow currentRow = data.NewRow();
XmlNodeList xnList = xmlDoc.SelectNodes("/response/result/" + moduleName +"/row[@no='" + row + "']");
foreach (XmlNode xn in xnList)
{
foreach (string field in fields)
{
XmlNode objNode = xn.SelectSingleNode("//FL[@val='" + field + "']");
if (objNode != null)
{
string value = objNode.InnerText;
currentRow[field] = value;
}
}
}
data.Rows.Add(currentRow);
}
data.EndLoadData();
这段代码适用于第1行,并将所有值完美地映射到DataColums。但是当涉及第2行(以及实际xml中的18个其他行)时,这些行的所有值将与第1行完全相同。因此,基本上我显示了第1行中的20个作为结果。不确定这里发生了什么,请帮我解决这个问题。感谢
答案 0 :(得分:0)
在我对你的字段进行定义之前,我无法对此进行全面测试。
// You will need to ensure these are right
DataTable data = new DataTable();
List<string> fields = new List<string>()
{
"LEADID", "SMOWNERID", "Lead Owner", "Company", "First Name", "Last Name", "Email", "Phone", "Lead Source", "Created By", "SMCREATORID", "MODIFIEDBY", "Modified By", "Created Time", "Modified Time", "Street", "City", "State", "Zip Code", "Last Activity Time", "Lead Type", "Practice name", "SMS Opt Out", "Send SMS"
};
foreach (var field in fields)
{
DataColumn column = new DataColumn(field, typeof(String));
data.Columns.Add(column);
}
string xmlText;
using (var client = new WebClient())
{
IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy;
defaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = defaultWebProxy;
xmlText = client.DownloadString(@"https://ix-infiniti-preview.azurewebsites.net/Manage/zohotest.xml");
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlText);
XmlNodeList xnList = xmlDoc.SelectNodes("/response/result/Leads/row");
foreach (var row in xnList)
{
XmlElement item = row as XmlElement;
Debug.WriteLine(item.Attributes["no"].Value);
DataRow currentRow = data.NewRow();
List<string> rowData = new List<string>();
foreach (XmlElement node in item.ChildNodes)
{
if (fields.Contains(node.Attributes["val"].Value))
{
Console.WriteLine(node.Attributes["val"].Value + ":" + node.InnerText);
currentRow[fields.IndexOf(node.Attributes["val"].Value)] = node.InnerText;
}
}
data.Rows.Add(currentRow);
}
data.AcceptChanges();