从多行文本框中读取多个文件

时间:2015-01-08 18:13:53

标签: xml c#-4.0

在这里,我开发了一个简单的工具,它可以读取xml文件并删除其中没有价格的节点。现在它读取一个XML文件。

但我需要读取多个XML文件并同时解析所有文件。有人可以帮我做同样的事。

private void LoadNewFile()
{
    OpenFileDialog XmlFile = new OpenFileDialog();
    XmlFile.Title = "Browse XML File";
    string FilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    XmlFile.InitialDirectory = FilePath;
    XmlFile.Filter = "XML Files|*.xml";
    System.Windows.Forms.DialogResult dr = XmlFile.ShowDialog();
    if (dr == DialogResult.OK)
    {
        OldFilePath = XmlFile.FileName;
    }
}

private void RemovePrice()
{
    XmlDocument xmldoc = new XmlDocument();
    XmlNodeList emptyElements;
    xmldoc.Load(NewFilePath);
    emptyElements = xmldoc.GetElementsByTagName("book");
    for (int i = emptyElements.Count - 1; i >= 0; i--)
    {
        string price= emptyElements[i]["price"].InnerText;
        if (string.IsNullOrEmpty(price))
            emptyElements[i].ParentNode.RemoveChild(emptyElements[i]);
    }
    xmldoc.Save(OldFilePath);
}

1 个答案:

答案 0 :(得分:1)

要加载多个文件,请使用Multiselect属性并将其设置为true。可以使用Parallel.ForEach循环完成并行处理。然后你只需稍微重写一下在这个框架中运行的main方法。下面是示例代码(未经过测试):

    private void ProcessFiles()
    {
        // This property should be set somewhere in the c-tor.
        // It's here just for presentation purposes.
        this.openFileDialog1.Multiselect = true;

        DialogResult dr = this.openFileDialog1.ShowDialog();
        if (dr == System.Windows.Forms.DialogResult.OK)
        {
            // Read the files 
            System.Threading.Tasks.Parallel.ForEach(
                this.openFileDialog1.FileNames,
                file =>
                    {
                        string oldFilePath = file;
                        string newFilePath = "Processed" + file;
                    });
        }
    }

    private void RemovePrice(string oldFilePath, string newFilePath)
    {
        XmlDocument xmldoc = new XmlDocument();
        XmlNodeList emptyElements;
        xmldoc.Load(newFilePath);
        emptyElements = xmldoc.GetElementsByTagName("book");
        for (int i = emptyElements.Count - 1; i >= 0; i--)
        {
            string price = emptyElements[i]["price"].InnerText;
            if (string.IsNullOrEmpty(price))
                emptyElements[i].ParentNode.RemoveChild(emptyElements[i]);
        }
        xmldoc.Save(oldFilePath);
    }