使用XML Reader在C#.net中查找并替换节点内部文本

时间:2018-08-03 17:00:44

标签: c# filestream xmldocument xmlreader xmlnode

我一直在编写以下代码,以查找错误的值并将其替换为正确的值。

我在这里有两个文件,Source =分隔的文本文件,如下所示。

J48309A0580113A27E053A2DEF40AC8B8,Z9e578475,
7e241974c714459997e20fe6e195ffb1,BD17946 and BD38168,

和我的目标xmlJRN文件如下所示。 (多个xmlJRN文件)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE eGAD SYSTEM "eGAD.Dtd">
<eGAD pakUID="PID_77F0F469AFE61B4A8121AA84EB349B6C">
  <document docID="1" docMasterID="1A5D331DDF8A84385F77B621C3F9CD86" docInstanceID="49E3D61E9CE1DF43BDD042F296913C88">
    <VendorId>7618CEADE31441C99FE1BC07E325E0FA</VendorId>
    <DocTypeId>CE3CD095580647389ED402675B43BE16</DocTypeId>
    <AccNo>TXT:</AccNo>
    <StmtDate>20161128</StmtDate>
    <DDSDocValue name="UniqueDocID" type="text" len="32">J48309A0580113A27E053A2DEF40AC8B8</DDSDocValue>
    <NumberOfPages value="8"/>
    <Skipped>
      <SPages></SPages>
    </Skipped>
  </document>
  <document docID="1" docMasterID="1A5D331DDF8A84385F77B621C3F9CD86" docInstanceID="49E3D61E9CE1DF43BDD042F296913C88">
    <VendorId>7618CEADE31441C99FE1BC07E325E0FA</VendorId>
    <DocTypeId>CE3CD095580647389ED402675B43BE16</DocTypeId>
    <AccNo>TXT:1</AccNo>
    <StmtDate>20161128</StmtDate>
    <DDSDocValue name="UniqueDocID" type="text" len="32">P48309A0580113A27E053A2DEF40AC8B8</DDSDocValue>
    <NumberOfPages value="8"/>
    <Skipped>
      <SPages></SPages>
    </Skipped>
  </document>
</eGAD>

我想做的是,我从文本文件中读取了第一个GUID,并将其与每个JRNxml的文档组进行比较,如果找到匹配的方式,我将用文本文件的第二个值替换innertext值。

下面是我的代码

static void Main()
{
    //Load the File
    using (StreamReader reader = new StreamReader("C:\\temp1\\AllXMLData_FinalOutput.txt"))
    {
        string line = reader.ReadLine();
        string[] value = new string[0];

        while ((line = reader.ReadLine()) != null)
        {
            // Load the file and read the GUID and Plan number one by one From Source Text file
            var values = line.Split(',');

            string GUIDfromTxt = values[0];  // Holds the GUID value from the Source Txt file
            string PlanNofromTxt = values[1]; // Holds the Plan number valuse from the Source Txt file

            // Read the XML's one by one from Destination folder and search for the GUID on each group
            string folderPath = "C:\\Temp2";
            DirectoryInfo di = new DirectoryInfo(folderPath);
            FileInfo[] rgFiles = di.GetFiles("*.JRN");

            foreach (FileInfo fi in rgFiles)
            {
                XmlDocument xmljrndoc = new XmlDocument();
                XmlNodeList xmlnode;                     
                FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite);  // Open file
                xmljrndoc.Load(fs);
                xmlnode = xmljrndoc.GetElementsByTagName("document");
                string JRNGUID = "";
                string JRNPLAN = "";

                for (int k = 0; k < xmlnode.Count; k++)                      // Read all the elements one by one
                { 
                    JRNGUID= xmlnode[k].SelectSingleNode("DDSDocValue[@name='UniqueDocID']").InnerText.Trim();   //get guid value from Destination XML
                    JRNPLAN= xmlnode[k].SelectSingleNode("AccNo").InnerText.Trim();                              //get Plan number value from Destination XML

                    Console.WriteLine("Value From Text File GUID : " + GUIDfromTxt + " Plan Number : " + PlanNofromTxt);
                    Console.WriteLine("Value From JRN File GUID : " + JRNGUID + " Plan Number : " + JRNPLAN);

                    if ((GUIDfromTxt == JRNGUID) && (JRNPLAN.Length <= 8)) // check the GUID matches
                    {
                        Console.WriteLine("OLD Value : "+ JRNPLAN + " NEW Value : " + PlanNofromTxt);                           xmlnode[k].SelectSingleNode("AccNo").InnerText.Replace(JRNPLAN, PlanNofromTxt); //  replace the txt plan to xml plan tag
                    }

                    Console.WriteLine("Xml JRN Value after find and replace " + JRNGUID + " " + JRNPLAN);                           
                }

                fs.Close();
                //fs.Dispose();

            }

            Console.ReadKey(); 
        }
        //reader.Close();
        //reader.Dispose();
    }
}

此代码在最后一部分中不起作用,无法替换xmlJRN文件中的文本。

有人可以帮助我找到我在这里犯的错误吗?非常感谢您的帮助。我想替换一个值并保存文件。

EDIT1: 感谢您的建议,我已经完成了代码。这是最后一个。

static void Main()
{
    StreamWriter sw = new StreamWriter("C:\\Temp3\\Log.txt", false, Encoding.ASCII);  // log file declaration

    string folderPath = "C:\\Temp2";
    DirectoryInfo di = new DirectoryInfo(folderPath);
    FileInfo[] rgFiles = di.GetFiles("*.JRN");

    foreach (FileInfo fi in rgFiles)
    {
        sw.WriteLine("Opening XML JRN File : " + fi.Name);

        XmlDocument xmljrndoc = new XmlDocument();
        XmlNodeList xmlnode;
        FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite);
        xmljrndoc.Load(fs);
        xmlnode = xmljrndoc.GetElementsByTagName("document");
        string JRNGUID = "";
        string JRNPLAN = "";

        for (int k = 0; k < xmlnode.Count; k++)                      // Read all the elements one by one
        {
            JRNGUID = xmlnode[k].SelectSingleNode("DDSDocValue[@name='UniqueDocID']").InnerText.Trim();   //get guid value from Destination XML
            JRNPLAN = xmlnode[k].SelectSingleNode("AccNo").InnerText.Trim();

            sw.WriteLine("FROM XMLJRN file - GUID : " + JRNGUID + " PlanNumber : " + JRNPLAN);

            StreamReader reader = new StreamReader("C:\\temp1\\AllXMLData_FinalOutput.txt");
            sw.WriteLine("Reading Txt file for GUID Search... ");
            string line = reader.ReadLine();
            string[] value = new string[0];

            while ((line = reader.ReadLine()) != null)
            {
                // Load the file and read the GUID and Plan number one by one
                var values = line.Split(',');

                string GUIDfromTxt = values[0];  // Holds the GUID value from the Txt file
                string PlanNofromTxt = "Compass:" + values[1]; // Holds the Plan number valuse from the Txt file

                sw.WriteLine("FROM text file - GUID : " + GUIDfromTxt + " PlanNumber : " + PlanNofromTxt);

                if ((GUIDfromTxt == JRNGUID) && (JRNPLAN.Length <= 8))                                  // check the GUID matches
                {
                    sw.WriteLine("GUID MATCH FOUND!");
                    sw.WriteLine("OLD Value : " + JRNPLAN + " replaced with  NEW Value : " + PlanNofromTxt);
                    fs.Close();
                    FileStream fs1 = new FileStream(fi.FullName, FileMode.Append, FileAccess.Write);

                    xmljrndoc.Save(@"C:\\Temp3\\" + fi.Name); //  replace the txt plan to xml plan tag
                    fs1.Close();

                    // xmljrndoc.Save(fi.FullName);

                }
                else
                {
                    sw.WriteLine("GUID MATCH NOT FOUND!");
                }

            }

        }
    }
            sw.Close();
}

1 个答案:

答案 0 :(得分:0)

String.Replace实际上并不直接修改字符串。它返回带有副本的字符串的副本。您仍然需要自己将修改后的值分配给InnerText。

例如,代替:

xmlnode[k].SelectSingleNode("AccNo").InnerText.Replace(JRNPLAN, PlanNofromTxt);

您需要执行以下操作:

var node = xmlnode[k].SelectSingleNode("AccNo");
node.InnerText = node.InnerText.Replace(JRNPLAN, PlanNofromTxt);