Member 12708425 Ответов: 3

Прочитав несколько .XML из каталога, по одному за раз.


У меня есть следующий пример кода.Он принимает входные файлы. xml из каталога (фиксированное местоположение) и преобразует существующий файл .xml в новую форму и помещает его в каталог d:\.

Теперь у меня есть несколько xml-файлов в исходном каталоге. Мне нужно прочитать каждый xml-файл по одному, преобразовать его в нужный вывод и сохранить в целевом каталоге.

Может ли какой-нибудь бу помочь мне сделать то же самое?
Обратите внимание, что я новичок в C#.

Мой код таков.

Что я уже пробовал:

using.System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
       XmlDocument doc = new XmlDocument();
            doc.Load("D:\\xml_file\\abcd_present.xml");
//I think I need to write here somthing to read the files one by one through some for loop.But it is not exactly getting done.Here I require some help.
XmlTextWriter writer = new XmlTextWriter("d:\\product.xml",system.Text.Encoding.UTF8);         
            writer.WriteStartDocument(true);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 2;
            writer.Flush();
            writer.WriteStartElement("root");
            // loop through each file 
           //cycle through each child node 
            String regionName = "", stationName = "", devicetype = "", device = "", startDate = "", endDate = "";
            int childNodes = doc.DocumentElement.ChildNodes.Count;
            foreach (XmlNode node in doc.DocumentElement.ChildNodes)
            {
// first node is the url ... have to go to next loc node                                 
{ 
//do existing .xml file conversion (I have the code for the same)
}
}
}
}
}

3 Ответов

Рейтинг:
2

Member 12708425

Спасибо всем за Вашу поддержку. Я новичок и научился по-другому делать то же самое.Я сделал следующее кодирование.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int j = 0;
            XmlDocument doc = new XmlDocument();
            var path = @"D:\XMLFiles";
            foreach (var file in System.IO.Directory.GetFiles(path))
            //doc.Load("C:\\Users\\hab77\\Desktop\\ERP xml file\\XMLFiles\\tarun20170526191139_present.xml");
            //High Alarm NTAMC.SCADA16.REGION.WR2.BOISAR400.BUS.220KV_BUS_1.HZ=50.0142 Status=GOOD
            // string path = "C:\\Users\\hab77\\Desktop\\ERP xml file\\XMLFiles";
            //foreach (string fileName in Directory.GetFiles("C:\\Users\\hab77\\Desktop\\ERP xml file\\XMLFiles", "*.xml"))
            {
                doc.Load(file);

                XmlTextWriter writer = new XmlTextWriter("d:\\ERP_XML_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + "_" + j + ".xml", System.Text.Encoding.UTF8);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2;
                writer.Flush();
                writer.WriteStartElement("root");
                // loop through each file 
                //cycle through each child node 
                String regionName = "", substationName = "", devicetype = "", device = "", startDate = "", endDate = "";
                int childNodes = doc.DocumentElement.ChildNodes.Count;
                foreach (XmlNode node in doc.DocumentElement.ChildNodes)
                {
                    // first node is the url ... have to go to nexted loc node 
                    // foreach (XmlNode locNode1 in node)
                    // {
                    if (node.Name == "Event")
                    {
                        childNodes = node.ChildNodes.Count;
                        writer.WriteStartElement("Event");
                        foreach (XmlNode locNode in node)
                        {
                            if (locNode.Name == "TriggerData")
                            {
                                // get the content of the loc node 
                                string loc = locNode.InnerText;
                                Console.WriteLine(loc + Environment.NewLine);
                                int num = loc.IndexOf(".HZ", 0);
                                String s1 = loc.Substring(0, num);
                                num = num + 1;
                                String s2 = loc.Substring(num, loc.Length - num);//HZ and status
                                string[] status = s2.Split(' ');
                                string[] words = s1.Split('.');
                                //string[] info13 = loc.Split('.').Select(str => str.Trim()).ToArray();
                                int i = 0;
                                //String regionName = "", substationName = "", devicetype = "", device = "";
                                int len = words.Length;
                                foreach (String s in words)
                                {

                                    //XmlDocument xm = new XmlDocument();
                                    if (i % 7 == 3)
                                    {
                                        regionName = s;
                                    }

                                    if (i % 7 == 4)
                                    {
                                        substationName = s;
                                    }

                                    if (i % 7 == 5)
                                    {
                                        devicetype = s;
                                    }
                                    if (i % 7 == 6)
                                    {
                                        device = s;
                                    }
                                    //createNode(regionName, substationName, deviceName,writer);
                                    //Console.WriteLine(xm.InnerXml);
                                    //Console.ReadKey();
                                    Console.WriteLine(s + Environment.NewLine);
                                    i++;
                                    Console.WriteLine(i);
                                }
                                foreach (String s in status)
                                {
                                    int num1 = s.IndexOf("=", 0);
                                    num1++;
                                    String s3 = s.Substring(num1, s.Length - num1);
                                    if (s.Contains("HZ"))
                                    {
                                        writer.WriteStartElement("HZ");
                                        writer.WriteString(s3);
                                        writer.WriteEndElement();
                                    }
                                    if (s.Contains("Status"))
                                    {
                                        writer.WriteStartElement("Status");
                                        writer.WriteString(s3);
                                        writer.WriteEndElement();
                                    }
                                }
                                //if condition
                                writer.WriteStartElement("Region");
                                writer.WriteString(regionName);
                                writer.WriteEndElement();
                                writer.WriteStartElement("Substation");
                                writer.WriteString(substationName);
                                writer.WriteEndElement();
                                writer.WriteStartElement("devicetype");
                                writer.WriteString(devicetype);
                                writer.WriteEndElement();
                                writer.WriteStartElement("device");
                                writer.WriteString(device);
                                writer.WriteEndElement();
                                writer.WriteEndElement();
                                // write it to the console so you can see its working 
                                //Console.WriteLine(loc + Environment.NewLine);
                            }
                            if (locNode.Name == "StartDate")
                            {
                                startDate = locNode.InnerText;
                                writer.WriteStartElement("StartDate");
                                writer.WriteString(startDate);
                                writer.WriteEndElement();
                            }
                            if (locNode.Name == "EndDate")
                            {
                                endDate = locNode.InnerText;
                                writer.WriteStartElement("EndDate");
                                writer.WriteString(endDate);
                                writer.WriteEndElement();
                            }
                            // get the content of the loc node                                                     
                        }
                    }
                    // there are a couple child nodes here so only take data from node named loc
                }
                writer.WriteEndDocument();
                writer.Close();
                //}
                j++;
            }
        }
        //function to add sftp copy.
    }

}


Рейтинг:
0

Graeme_Grant

Вот как работать с несколькими файлами в каталоге:

namespace ProcessDirectory
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            //var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var path = @"d:\xmlfiles";

            foreach (var file in System.IO.Directory.GetFiles(path))
            {
                ProcessFile(file);
            }
            Console.ReadKey();
        }

        static void ProcessFile(string Filename)
        {
            // do processing here...
            Console.WriteLine(Filename);
        }
    }
}


Member 12708425

Мне нужно указать конкретное место.d:\xmlfiles\ как мои файлы находятся там внутри d:\xmlfiles справочник.Как указать это вместо "MyDocuments").

Graeme_Grant

Измените переменную path на все, что вы хотите. Я изменил решение для вас.

Member 12708425

var path = @"D:\\XMLFiles";                    foreach (var file in System.IO.Directory.GetFiles(path))                                        {                        doc.Load("file"); 

Значение файла приходит как null.

Я пытался d:\XMLFiles тоже.Это также приводит к тому, что "файл" становится нулевым.

Graeme_Grant

var path = @"D:\\XMLFiles";

@ ""- это строковый литерал, поэтому дополнительная обратная косая черта '\' не требуется - вам не нужно "экранировать" специальные символы. Вот почему у меня был только один провал:
var path = @"d:\xmlfiles";

Вот более подробная информация о Строковые литералы (C#)[^]

Graeme_Grant

Снова побежал с буквальным строковым путем и здесь работает правильно. Все, что я могу придумать, если не возникнет никакой ошибки, - это то, что в папке нет файлов.

Member 12708425

У меня есть solution.as ниже.

var path = @"D:\XMLFiles";
                    foreach (var file in System.IO.Directory.GetFiles(path))
{
doc.Load(file);
                    
                    XmlTextWriter writer = new XmlTextWriter("d:\\product_"+j+".xml", System.Text.Encoding.UTF8);


Но я хочу, чтобы файлы создавались как Product_CurrentdateTime.xml формат.Теперь он создает как Product_0.xml,Product_1.xml файл.
Вы можете что-нибудь предложить?

Graeme_Grant

var filename = $"Product_{DateTime.Now.ToString("yyyyMMdd-hhmmss")}.xml";

Member 12708425

Я тоже получил то же самое.Следующее-По желанию.

XmlTextWriter writer = new XmlTextWriter("d:\\product_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + "_" +j+ ".xml", System.Text.Encoding.UTF8); 

Member 12708425

Теперь я хочу скопировать файлы в определенное место sftp в той же программе.
Как я могу это сделать?

Graeme_Grant

Начните новый вопрос, так как это выходит за рамки оригинала.

Рейтинг:
0

radha patil

привет попробуй это

 XmlDocument xdoc = new XmlDocument();
                xdoc.Load(Server.MapPath("xml/sample.xml"));
                XmlNodeList NodeList = xdoc.SelectNodes("root/*");
                foreach (XmlNode Node in NodeList)
                {
                    if (Node.Attributes[0].InnerText.ToLower().Equals("p4"))
                    {
}