2017-04-13 3 views
0

が、このから要素で日付を変換する必要があります。これにC#を使用してXML文字列の日付を置き換えるにはどうすればよいですか?私はXMLのRSSフィードを解析しようとしています

<lastBuildDate>Thu, 13 Apr 2017</lastBuildDate>

<lastBuildDate>Thu, 13 Apr 2017 09:00:52 +0000</lastBuildDate>

私はのホールドを取得することができていますlastBuildDate以下のコードの要素

XmlTextReader reader = new XmlTextReader(rssFeedUrl); 
while (reader.Read()) 
{ 
    if (reader.NodeType == XmlNodeType.Element && reader.Name.Contains("BuildDate")) 
    { 
    // replace DateTime format 
    } 
} 

私は要素のテキストの値を取得する方法を知らない&正しい形式で置き換える - 誰でも助けることができますか?

+0

全体を解析せずに要素を探し、 'innerText'を置き換えて、再度文字列化するのはなぜですか?そうではない。あなたはそれで何をしていますか? –

+0

'XElement'を使うべきです。それはずっと簡単です。 – SLaks

+0

スレッドのタイトルを更新しました.XmlTextReaderを使用する必要はありません。これをどのようにするか私に教えてください。 –

答えて

1

私はXMLにLINQを使用してお勧めしたい、それが非常に良くAPIです:

var doc = XDocument.Load(rssFeedUrl); 

var lastBuildDate = doc.Descendants("lastBuildDate").Single(); 

var lastBuildDateAsDateTime = (DateTime) lastBuildDate; 

lastBuildDate.Value = "new value here"; // perhaps based on lastBuildDateAsDateTime above 

// get XML string with doc.ToString() or write with doc.Save(...) 

は、作業のデモ用this fiddleを参照してください。

1

これは方法です。私はXmlDocumentが好きです。他の方法もありますが、これはあなたに行くでしょう。

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Xml; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
    public static void Main() 
     { 
      XmlDocument doc = new XmlDocument(); 
      doc.LoadXml("<?xml version='1.0' encoding='UTF-8' standalone='no'?><root><lastBuildDate>Thu, 13 Apr 2017</lastBuildDate></root>"); 

      XmlNodeList list = doc.GetElementsByTagName("lastBuildDate"); 

      foreach(XmlNode node in list) 
      { 
       DateTime result = new DateTime(); 
       if (DateTime.TryParse(node.InnerXml, out result)) 
       { 
        node.InnerText = result.ToString("ddd, d MMM yyyy HH:mm:ss") + "+0000"; //Thu, 13 Apr 2017 09:00:52 +0000 
       } 
      } 
      using (var stringWriter = new StringWriter()) 
      using (var xmlTextWriter = XmlWriter.Create(stringWriter)) 
      { 
       doc.WriteTo(xmlTextWriter); 
       xmlTextWriter.Flush(); 
       Console.Write(stringWriter.GetStringBuilder().ToString()); 
      } 
     } 
    } 
} 
関連する問題