2011-05-30 89 views
2

我从包含名称和地址等客户数据的Web服务中获取肥皂信封。该地址不包含城市/郊区,但包含邮政编码。我将所有城市和郊区的邮政编码存储在CSV文件中,因此我想为每个邮政编码插入正确的名称。我可以将其存储在数据库或其他内容中,但这更关于如何在传递数据之前插入节点。将XmlNode添加到XmlElement

的代码是这样的:

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; 
       } 
     } 
    } 
} 

,我不知道该怎么做,我注释掉的代码。有什么建议么?有关如何使这种效率更高的提示也值得赞赏。

在此先感谢。

回答

2

好吧,如果不真的看到存在的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); 
} 
+0

点上,然而,它增加了的xmlns到节点,例如:<郊区的xmlns = “”>纽卡斯尔。感谢词典例子,我会看看那个 – Roger 2011-05-30 14:25:21

+0

嗯。尝试使用“ns:suburb”作为节点名称 - 您正在使用ns:前缀选择“postcode”元素。 – 2011-05-30 15:00:29