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

问题描述 投票:0回答:1

我一直在编写下面的代码来找到并用正确的值替换错误的值。

我这里有两个文件,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();
}
c# filestream xmldocument xmlreader xmlnode
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.