2013-02-27 95 views
-2
<Day> 
<Monday>true</Monday> 
<Tuesday>false</Tuesday> 
<Wednesday>true</Wednesday> 
<Thursday>false</Thursday> 
<Friday>true</Friday> 
<Saturday>false</Saturday> 
<Sunday>true</Sunday> 
</Day> 
<Time> 
<dateTime>12:21</dateTime> 
</Time> 

我需要讀取上述xml文件以獲取日期和時間,並將數據提取到變量。如何用c#實現這個?使用C讀取XML文件#

+0

請參閱http://stackoverflow.com/questions/2565064/reading-an-xml-file-with-net?rq=1 – 2013-02-27 06:05:05

+0

是它整個XML,或只是其中的一部分?預期的結果是什麼?應該提取哪一天或哪幾天?你有什麼嘗試? – 2013-02-27 06:34:19

+0

你問的問題讓別人完成你的工作... – giammin 2013-03-05 15:22:54

回答

1

我提供一個控制檯程序加載從字符串的XML。您可以從文件中提供的文件路徑以及加載..(我已經提到過的語句)..

這是你的XML:

string xml = @"<testxml><Day> 
<Monday>true</Monday> 
<Tuesday>false</Tuesday> 
<Wednesday>true</Wednesday> 
<Thursday>false</Thursday> 
<Friday>true</Friday> 
<Saturday>false</Saturday> 
<Sunday>true</Sunday> 
</Day> 
<Time> 
<dateTime>12:21</dateTime> 
</Time> 
</testxml>"; 

現在宣佈的XmlDocument()和加載XML進去..

 XmlDocument xDoc = new XmlDocument(); 
     xDoc.LoadXml(xml); 
     //xDoc.Load(xmlpath); 

現在你的xml文檔已經準備好了,用xDoc.Load(xmlpath);可以從文件路徑加載。

現在您要訪問節點提供的XPath ..或者使用的selectSingleNode使用節點列表(的SelectNodes)或只是一個節點..:

我使用的selectNodes天..和對的selectSingleNode日期時間。

  string xpath = "/testxml/Day/*"; 
      XmlNodeList xNode = xDoc.SelectNodes(xpath); 

      foreach (XmlNode node in xNode) 
      { 
       string day = node.LocalName; 
       Console.WriteLine(day + ", value=\"" + node.InnerText + "\""); 
      } 

上面的代碼打印節點名稱(即天,並將其值真/假)

現在,讓我們打印的日期時間值:

  xpath = "/testxml/Time/dateTime"; 
      XmlNode node1 = xDoc.SelectSingleNode(xpath); 
      Console.WriteLine(node1.LocalName + ", value=\"" + node1.InnerText + "\""); 

這是與XML DOM玩簡單的例子:)

現在整個代碼:

 static void Main(string[] args) 
     { 
      string xml = @"<testxml><Day> 
<Monday>true</Monday> 
<Tuesday>false</Tuesday> 
<Wednesday>true</Wednesday> 
<Thursday>false</Thursday> 
<Friday>true</Friday> 
<Saturday>false</Saturday> 
<Sunday>true</Sunday> 
</Day> 
<Time> 
<dateTime>12:21</dateTime> 
</Time> 
</testxml>"; 

      XmlDocument xDoc = new XmlDocument(); 
      xDoc.LoadXml(xml); 
      //xDoc.Load(xmlpath); 

      string xpath = "/testxml/Day/*"; 
      XmlNodeList xNode = xDoc.SelectNodes(xpath); 

      foreach (XmlNode node in xNode) 
      { 
       string day = node.LocalName; 
       Console.WriteLine(day + ", value=\"" + node.InnerText + "\""); 
      } 

      xpath = "/testxml/Time/dateTime"; 
      XmlNode node1 = xDoc.SelectSingleNode(xpath); 
      Console.WriteLine(node1.LocalName + ", value=\"" + node1.InnerText + "\""); 
      Console.ReadLine(); 
     } 

希望它有幫助..讓我知道如果您有任何問題..

+0

謝謝。這會做。 – user004 2013-02-27 11:20:43

0

你有什麼嘗試?

看看類XDocument。在那裏,你可以這樣做

XDocument document = XDocument.Load(XMLPATH); 
IEnumerable<XElement> day = document.Elements("Day"); 
+0

我沒有嘗試,因爲我是新來的C#。我正在尋找想法。謝謝你的回答 – user004 2013-02-27 06:13:05