从xml /文本文件动态创建文本文件

问题描述:

我可以使用以前创建的xml文件和文本文件中的数据从ac#程序动态创建文本文件,我已经写了一半的代码,但无法继续。请帮助从xml /文本文件动态创建文本文件

using System; 
using System.IO; 
using System.Xml; 

namespace Task3 
{ 

    class TextFileReader 
    { 

     static void Main(string[] args) 
     { 
     String strn=" ", strsn=String.Empty; 
     XmlTextReader reader = new XmlTextReader("my.xml"); 

       while (reader.Read()) 
       { 
        switch (reader.NodeType) 
        { 
         case XmlNodeType.Element: // The node is an element. 
          if (reader.HasAttributes) 
          { 
          strn = reader.GetAttribute(0); 
          strsn = reader.GetAttribute(1); 
          int counter = 0; 
          string line; 
          // Read the file and display it line by line. 
          System.IO.StreamReader file = new System.IO.StreamReader("read_file.txt"); 
          string ch, ch1; 
          while ((line = file.ReadLine()) != null) 
          { 
           if (line.Substring(0, 1).Equals("%")) 
           { 
            int a = line.IndexOf('%'); 
            int b = line.LastIndexOf('%'); 
            ch = line.Substring(a + 1, b - 1); 
            ch1 = line.Substring(a, b+1); 
            if (ch == "name") 
            { 
             string test = line.Replace(ch1, strn); 
             Console.WriteLine(test); 
            } 
            else if (ch == "sirname") 
            { 
             string test = line.Replace(ch1, strsn); 
             Console.WriteLine(test); 
            } 
           } 
           else 
           { 
            Console.WriteLine(line); 
           } 
           counter++; 
          } 
          file.Close(); 
          } 
          break; 
        } 

       }   

     // Suspend the screen. 
     Console.ReadLine(); 
     } 
    } 
} 

从我读XML文件是:

<?xml version="1.0" encoding="utf-8" ?> 
<Workflow> 
    <User UserName="pqr" Sirname="sbd" /> 
    <User UserName="abc" Sirname="xyz" /> 
</Workflow> 

而且文本文件是:

hi this is me 
%sirname% 
%name% 

但这不是我want..please帮助

+1

你真正的问题是什么?你想做什么??你想要什么? – 2010-04-09 09:01:22

+1

请发布您期望看到的输出示例。 – JBRWilkinson 2010-04-09 09:01:37

+1

如果这不是你想要的,你想要**做什么**?你是否有问题写入另一个文件,或者你没有得到你想要的输出? – Patrick 2010-04-09 09:05:46

您是否考虑过使用XSLT?定义一个.xsl文件很容易,它可以将您的XML“转化”为格式化的文本文件,这似乎是您想要做的。

我认为,你真正想做的是用xml中的数据替换像%sirname%这样的标记。您已经成功读取了xml并编写了文本文件。所以你的问题仍然存在:如何替换% -symbols之间的令牌?

我建议使用正则表达式。请参阅this explenation,如果遇到困难,请提出更具体的问题。

+0

我非常想用新值创建一个新的文本文件,而且我希望这个程序shud检查%标记中的值,将其与XML文件中的属性名称进行比较,然后将其替换为由此生成的新文本文件中的属性值,但我无法动态检查n比较标记n属性 – techstu 2010-04-09 09:58:37