【问题标题】:Find and Replace the node inner text in C#.net using XML Reader使用 XML Reader 在 C#.net 中查找和替换节点内部文本
【发布时间】:2019-01-11 14:44:58
【问题描述】:

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

我这里有两个文件,Source=Delimited 文本文件,如下所示。

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 的文档组进行比较,如果我发现匹配意味着,我将用文本文件的第二个值替换内部文本值。

下面是我的代码

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 文件中的文本。

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

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

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

【问题讨论】:

  • 我建议为您的所有流媒体对象实现 using 块。
  • 当你使用“Using”块而不是普通块时会发生什么?

标签: c# filestream xmldocument xmlreader xmlnode


【解决方案1】:

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

例如,而不是:

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

您需要执行以下操作:

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

【讨论】:

  • 你有任何参考资料吗,我可以在某处看到瑞克?我提到的任何链接..应该对我有帮助
  • msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx 解释了 String.Replace。我编辑了答案以提供一个示例,希望有助于澄清我的意思。希望有帮助!
  • 谢谢伙计,我已经完成了这个!将在这里分享我的最终代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
相关资源
最近更新 更多