由于工作中的一些决定,我最近将注意力从 VB.NET 转移到了 C#。我现在在尝试从 XML 文件中读取数据时遇到了一个问题。
在这里,XML 看起来像这样
<?xml version="1.0" encoding="utf-8"?>
<shipmentdata>
<shipment shipmentid="70716481780000102" messageid="2">
<msgcreated>2012-06-14T10:44:00</msgcreated>
<orderdate>2012-06-14</orderdate>
<services>
<baseservice ediid="ZG8">Replenishment</baseservice>
<addedservices>
<addedservice id="2" ediid="Z47">Installation</addedservice>
<addedservice id="3" ediid="Z45">Swap</addedservice>
</addedservices>
</services>
<weight uom="KGM">2</weight>
<bulkref>123456</bulkref>
</shipment>
</shipmentdata>
我得到的 C# 代码是这样的:
private DataSet ReturnServices(string FileName)
{
XmlDocument m_xmld = new XmlDocument();
XmlNodeList m_nodelist;
m_xmld.Load(FileName);
m_nodelist = m_xmld.SelectNodes("/shipmentdata");
DataRow aDR;
DataTable aDT = new DataTable("AddedServices");
aDT.Columns.Add("ediid",typeof(string));
aDT.Columns.Add("shipmentid",typeof(string));
DataSet oDS = new DataSet("EDIinfo");
foreach (XmlElement m_node in m_nodelist)
{
ShipmentID = m_node["shipment"].Attributes.
GetNamedItem("shipmentid").Value.ToString();
XmlNodeList s_nodelist = m_xmld.SelectNodes(
"/shipmentdata/shipment/services/addedservices");
foreach (XmlElement s_node in s_nodelist)
{
aDR = aDT.NewRow();
aDR["ediid"] = s_node.ChildNodes.Item(0).Attributes.
GetNamedItem("ediid").Value.ToString();
aDR["shipmentid"] = ShipmentID;
aDT.Rows.Add(aDR);
}
}
oDS.Tables.Add(aDT);
return oDS;
}
这里的问题是,虽然文件包含两个附加服务(Z47 和 Z45),但由于某种原因,只有第一个节点存储在 DataTable(Z47)中。如何循环遍历所有添加的服务节点?
任何帮助将不胜感激,我已经坚持了一段时间,并开始意识到我可能陷入了难以摆脱的思路和逻辑。:P