【问题标题】:Add XmlNode to XmlElement将 XmlNode 添加到 XmlElement
【发布时间】:2011-05-30 14:03:32
【问题描述】:

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

我不确定在注释掉代码的地方该怎么做。有什么建议么?关于如何提高效率的提示也将不胜感激。

提前致谢。

【问题讨论】:

    标签: c# .net xml xmlnode


    【解决方案1】:

    嗯,如果不实际看到现有的 XML 结构和所需的新 XML 结构,就很难知道这一点。基本上我会假设您想要一个包含与postcode 元素相同级别的郊区的新 XML 节点。

    在那种情况下,我会使用:

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

    【讨论】:

    • 点对点,但是,它将 xmlns 添加到节点,例如:Newcastle。感谢您的字典示例,我会看看那个
    • 嗯。尝试使用“ns:suburb”作为节点名称 - 您正在使用 ns: 前缀选择 postcode 元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多