将XmlNode添加到XmlElement

问题描述

| 我从Web服务中获得了一个肥皂信封,上面有客户数据,例如姓名和地址等。该地址不包含城市/郊区,但包含邮政编码。我在CSV文件中包含了所有城市和郊区及其邮政编码,因此我想为每个邮政编码插入正确的名称。我可以将其存储在数据库中或其他内容中,但这更多地是关于在传递数据之前如何插入节点。 代码如下:
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(searchResponse);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NaMetable);
nsmgr.AddNamespace(\"ns\",wsNamespace);

XmlNodeList postCodeNodes = xDoc.SelectNodes(\"//ns:postcode\",nsmgr);
string applicationPath = AppDomain.CurrentDomain.BaseDirectory;

foreach (XmlNode node in postCodeNodes)
{ 
    using (StreamReader readFile = new StreamReader(applicationPath + \"postcodes.csv\"))
    {
        string line;
        string[] row;

        while ((line = readFile.ReadLine()) != null)
        {
                row = line.Split(\',\');
                if (row[0].ToString() == node.InnerText)
                {
                    string suburb = row[1].ToString();
                    //XmlNode ndSuburb = xDoc.CreateElement(\"suburb\");
                    //ndSuburb.Value = suburb;
                    //node.ParentNode.AppendChild(ndSuburb);
                    break;
                }
        }
    }
}
而且我不确定在注释掉代码的地方该怎么做。有什么建议么?也将了解如何使此效率更高的提示。 提前致谢。     

解决方法

        好吧,如果没有实际看到存在的XML结构和所需的新XML结构,就很难知道。基本上,我假设您想要一个新的XML节点,该节点包含与
postcode
元素相同级别的郊区。 在这种情况下,我使用了:
XmlElement elem = xDoc.CreateElement(\"suburb\");
elem.InnerText = ...;
node.ParentNode.AppendChild(elem);
编辑 关于效率:为什么不只读一次“邮政编码文件”,而是将条目添加到包含邮政编码作为关键字和值作为郊区的字典中?这比每次读取文件都要快得多。
Dictionary<string,string> postCodeMap = new Dictionary<string,string>();
string[] lines = File.ReadAllLines(...);
foreach (string line in lines)
{
   string[] parts = line.Split(\',\');
   postCodeMap[parts[0]] = parts[1];
}
然后做:
foreach (XmlNode node in postCodeNodes)
{ 
    string suburb = postCodeMap[node.InnerText];

    XmlElement elem = xDoc.CreateElement(\"suburb\");
    elem.InnerText = suburb;
    node.ParentNode.AppendChild(elem);
}