2010-04-09 85 views
1

我可以使用以前創建的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

回答

1

您是否考慮過使用XSLT?定義一個.xsl文件很容易,它可以將您的XML「轉化」爲格式化的文本文件,這似乎是您想要做的。

1

我認爲,你真正想做的是用xml中的數據替換像%sirname%這樣的標記。您已經成功讀取了xml並編寫了文本文件。所以你的問題仍然存在:如何替換% -symbols之間的令牌?

我建議使用正則表達式。請參閱this explenation,如果遇到困難,請提出更具體的問題。

+0

我非常想用新值創建一個新的文本文件,而且我希望這個程序shud檢查%標記中的值,將其與XML文件中的屬性名稱進行比較,然後將其替換爲由此生成的新文本文件中的屬性值,但我無法動態檢查n比較標記n屬性 – techstu 2010-04-09 09:58:37