2016-06-17 63 views
0

我想產生以下的輸出:如何迭代所有節點?

<article> <status> </status> ....</article> 
<article> <status> </status> ....</article> 

我需要的循環邏輯點點的援助 - 在那裏我可能會錯誤的任何建議。我嘗試使用「for」循環,但是這不能產生所需的輸出。請指教。謝謝。

public static string createArticleALL() 
    { 

     XElement xeRoot = new XElement("article"); 
     XDocument xDoc = new XDocument(xeRoot); 

     using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["###"].ConnectionString)) 

     { 
      con.Open(); 

      using (SqlCommand command = new SqlCommand("####", con)) 
      { 

       SqlDataReader reader = command.ExecuteReader(); 
       while (reader.Read()) 
       { 
        string title = reader.GetString(0); 
        string body = reader.GetString(4); 

        string pub = reader["publication_id"].ToString(); 
        string iss = reader["issue_id"].ToString(); 
        string sid = reader["STORYID"].ToString(); 


        string c = url(title, pub, iss, sid); 

     DateTime dt = DateTime.Today; 

     foreach (XElement element in xDoc.Descendants("article")) 
     { 

     XElement xeStatus = new XElement("status", "Approved"); 
     xeRoot.Add(xeStatus); 

     XElement xeTitle = new XElement("title", title); 
     xeRoot.Add(xeTitle); 

     XElement xeSubTitle = new XElement("subtitle", title); 
     xeRoot.Add(xeSubTitle); 

     XElement xeSynopsis = new XElement("synopsis", body + "..."); 
     xeRoot.Add(xeSynopsis); 

     XElement xeURL = new XElement("url", c); 
     xeRoot.Add(xeURL); 

     XElement xeDisplayDate = new XElement("display_date", dt); 
     xeRoot.Add(xeDisplayDate); 


     } 


       } 
      } 


     return xDoc.ToString(); 
     } 
     return null; 

    } 
+0

1)你的代碼當前產生了什麼輸出? 2)你想要的輸出是無效的XML。有效的XML必須有一個[根元素](https://en.wikipedia.org/wiki/Root_element)。你不能使用'XDocument'來產生無效的XML。 – dbc

回答

0

清除了這一點。您必須創建一個article節點,並將其添加到每個while循環的文檔中。假設你沒有在其他地方使用標題,我刪除了額外的位。

XDocument xDoc = new XDocument(new XElement("Root")); 
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["###"].ConnectionString)) 
{ 
    con.Open(); 

    using (SqlCommand command = new SqlCommand("####", con)) 
    { 
     XElement article; 
     SqlDataReader reader = command.ExecuteReader(); 
     while (reader.Read()) 
     { 
      xDoc.Add(article = new XElement("article")); 
      article.Add(new XElement("status", "Approved")); 
      string title; 
      article.Add(new XElement("title", title = reader.GetString(0))); 
      article.Add(new XElement("subtitle", title)); 
      article.Add(new XElement("synopsis", reader.GetString(4) + "...")); 

      string pub = reader["publication_id"].ToString(); 
      string iss = reader["issue_id"].ToString(); 
      string sid = reader["STORYID"].ToString(); 

      string c = url(title, pub, iss, sid); 
      article.Add(new XElement("url", c)); 

      article.Add(new XElement("display_date", DateTime.Today)); 
     } 
    } 
}