2013-05-04 3 views
2

아직 성취 할 수없는 또 다른 과제가 있습니다. this site에서 XML을 구문 분석하고 해당 이름에 "VIDEO"가없는 노드를 모두 제거한 다음 다른 노드에 저장해야합니다. XML 파일. 나는 독서와 글쓰기에 아무런 문제가 없지만, 제거하면 어떤 어려움이 있습니다. > 부모 노드 - - 내가 노드하려고 노력했다> 아이 노드 작업 아루를하지만 유용한 것 같지 않았다XML 노드 제거

static void Main(string[] args) 
    { 
     using (WebClient wc = new WebClient()) 
     { 
      string s = wc.DownloadString("http://feeds.bbci.co.uk/news/health/rss.xml"); 
      XmlElement tbr = null; 
      XmlDocument xml = new XmlDocument(); 
      xml.LoadXml(s); 

      foreach (XmlNode node in xml["rss"]["channel"].ChildNodes) 
      { 
       if (node.Name.Equals("item") && node["title"].InnerText.StartsWith("VIDEO")) 
       { 
        Console.WriteLine(node["title"].InnerText); 
       } 
       else 
       { 
        node.ParentNode.RemoveChild(node); 
       } 
      } 

      xml.Save("NewXmlDoc.xml"); 
      Console.WriteLine("\nDone..."); 

      Console.Read(); 
     } 
    } 

나는 또한 잘 작동하지 않는에서 removeAll 방법을 시도 그것 때문에 "VIDEO"조건을 만족하지 않는 모든 노드를 제거합니다.

//same code as above, just the else statement is changed 
else 
{ 
    node.RemoveAll(); 
} 

도와 주시겠습니까?

답변

2

은 내가 Linq에 작업을하지 않은 ... Linq에이

var xDoc = XDocument.Load("http://feeds.bbci.co.uk/news/health/rss.xml"); 

xDoc.Descendants("item") 
    .Where(item => !item.Element("title").Value.StartsWith("VIDEO")) 
    .ToList() 
    .ForEach(item=>item.Remove()); 

xDoc.Save("NewXmlDoc.xml"); 

또한 XPath

foreach (var item in xDoc.XPathSelectElements("//item[not(starts-with(title,'VIDEO:'))]") 
         .ToList()) 
{ 
    item.Remove();    
} 
+1

매우 감사 사용할 수있는 사용하기 쉬운 XML로 찾아 많은, 지금까지, 그러나 꽤 쉽고 꽤 강력 해 보인다. 답변을 수락했습니다. – Storm

+0

질문이 하나 더 있을까요? 글쓰기를 콘솔로 변경하려고 시도했지만 어쨌든 작동하지 않습니다 ... foreach (xDoc.XPathSelectElements ("items with (starts-with (title, 'VIDEO :'))]"). ToList()) { Console.WriteLine ((string) item.Attribute ("title"))); }' – Storm

+1

@Storm'title'은 item의 * attribute *가 아닙니다. 하위 요소입니다. 'item.Element ("title") .Value' – I4V