2012-10-15 44 views
7

我試圖用不同的XML從另一個文件

見下面的代碼創建一個xmldocument對象創建的XmlDocument

編輯1 Compleate的代碼塊:

try 
{ 
     XmlDocument objNewsDoc = new XmlDocument(); 
     string strNewsXml = getNewsXml(); 
     objNewsDoc.LoadXml(strNewsXml); 

     var nodeNewsList = objNewsDoc.SelectNodes("news/newsListItem"); 
     XmlElement news = docRss.CreateElement("news"); 
     foreach (XmlNode objNewsNode in nodeNewsList) 
     { 
       string newshref = objNewsNode.Attributes["href"].Value; 
       string strNewsDetail = getNewsDetailXml(newshref); 
       try 
        { 
         objNewsDoc.LoadXml(strNewsDetail); 
         XmlNode importNewsItem = docRss.ImportNode(objNewsDoc.SelectSingleNode("newsItem"), true); 
         news.AppendChild(importNewsItem); 
        } 
        catch (Exception ex) 
        { 
          Console.Write(ex.Message); 
         } 

       } 

      docRss.Save(Response.Output); 
} 
catch (Exception ex) 
{ 
     Console.Write(ex.Message); 
} 

回答

10

您需要使用Import Node方法從第一文檔導入的XmlNode進入第二的背景下:

objNewsDoc.LoadXml(strNewsDetail);  // Current XML 
XmlDocument docRss = new XmlDocument(); // new Xml Object i Want to create 

XmlElement news = docRss.CreateElement("news"); // creating the wrapper news node 
//Import the node into the context of the new document. NB the second argument = true imports all children of the node, too 
XmlNode importNewsItem = docRss.ImportNode(objNewsDoc.SelectSingleNode("newsItem"), true); 
news.AppendChild(importNewsItem); 

編輯

你很接近你的回答,你現在的主要問題是你需要將你的新聞元素附加到你的主文檔中。我建議做以下的,如果你希望你的輸出文檔看起來像這樣:

<news> 
    <newsItem>...</newsItem> 
    <newsItem>...</newsItem> 
</news> 

而不是創建一個新的XmlElement,新聞,相反,當你創建docRSS,請執行以下操作:

XmlDocument docRss = new XmlDocument(); 
docRss.LoadXml("<news/>"); 

您現在有一個看起來像這樣的一個XmlDocument:

<news/> 

然後,而不是news.AppendChild,簡單地說:

docRSS.DocumentElement.AppendChild(importNewsItem); 

這附加在news元素(在本例中是文檔元素)下的每個newsItem

+0

+1的工作。但我仍然得到docrss爲空當我使用'docRss.Save(Response.Output);'輸出完成文檔 – Champ

+0

我已添加完整的代碼塊,你可以幫助嗎? – Champ

+0

你太親近了!問題是你已經創建了你想要的所有xml,但是你沒有將新聞元素添加到你的輸出文檔中。看到我更新的答案。 – dash

相關問題