2017-04-13 1 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'를 대체하고, 다시 문자열 화해야하는 이유는 무엇입니까? 아니면 restringify하지; 너는 그걸로 무엇을하고 있니? –

+0

당신은'XElement'를 사용해야합니다; 그것은 훨씬 쉽습니다. – SLaks

+0

스레드 제목을 업데이트 했으므로 XmlTextReader를 사용할 필요가 없습니다. 어떤 식 으로든이 일을하는 방법을 보여줄 수 있습니까? –

답변

1

, 그것은 훨씬 더 좋은 API입니다.

1

이것은 방법입니다. 나는 XmlDocument를 좋아한다. 다른 방법이 있지만 이것은 당신을 가게 할 것입니다.

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를 참조하십시오 : 나는 XML에 LINQ를 사용하는 것이 좋습니다 것

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()); 
      } 
     } 
    } 
} 
관련 문제