2015-10-03 44 views
0

我想在一個屬性中添加如此多的值。下面是我的代碼,如何在一個屬性中添加額外的值?

 XmlDocument doc = new XmlDocument(); 
     XmlElement root = doc.CreateElement("root"); 
     doc.AppendChild(root); 
     XmlElement mainelement; 
     mainelement = doc.CreateElement("main_element"); 
     root.AppendChild(mainelement); 
     string[] array = new string[] { "one", "two", "three" }; 
     for (int i = 0; i < 3; i++) 
     { 
      XmlElement subelement = doc.CreateElement("shop"); 
      subelement.SetAttribute("Name", ""); 
      subelement.SetAttribute("client", array[i]); 
      mainelement.AppendChild(subelement); 
     } 
     doc.Save(@"C:\simple.xml"); 

它給像輸出,

<root> 
    <main_element> 
    <shop Name="" client="one" /> 
    <shop Name="" client="two" /> 
    <shop Name="" client="three" /> 
    </main_element> 
</root> 

但我預計產量

<root> 
    <main_element> 
    <shop Name="" client="one,two,three" /> 
    </main_element> 
</root> 

幫我做這樣的改變。提前致謝。

+0

@ empereur-aiman的回答是對的。但是在一個XML角度也許你應該使用這樣的格式才能夠後對其進行處理: ' <店鋪名稱=「」> <客戶端ID =「一個」 /> <客戶端ID =「two」/> ' –

回答

-1

變化:

for (int i = 0; i < 3; i++) 
    { 
     XmlElement subelement = doc.CreateElement("shop"); 
     subelement.SetAttribute("Name", ""); 
     subelement.SetAttribute("client", array[i]); 
     mainelement.AppendChild(subelement); 
    }` 

要:

var combined = String.Join(",", array); 
XmlElement subelement = doc.CreateElement("shop"); 
subelement.SetAttribute("Name", ""); 
subelement.SetAttribute("client", combined); 
mainelement.AppendChild(subelement);` 

你寫的每一個項目,以它自己的子屬性,所以你要對傳遞到循環中每個字符串的元素。通過使用String.Join,您可以將您的字符串列表組合爲CSV,然後使用結果字符串作爲屬性值,從而獲得您要查找的結果。

0

您可以使用屬性的值構建字符串並分配它。

XmlDocument doc = new XmlDocument(); 
XmlElement root = doc.CreateElement("root"); 
doc.AppendChild(root); 
XmlElement mainelement; 
mainelement = doc.CreateElement("main_element"); 
root.AppendChild(mainelement); 

string[] array = new string[] { "one", "two", "three" }; 
XmlElement subelement = doc.CreateElement("shop"); 
subelement.SetAttribute("Name", ""); 

string clientAttribute = String.Join(",",array); 

subelement.SetAttribute("client", clientAttribute); 
mainelement.AppendChild(subelement); 
doc.Save(@"C:\simple.xml"); 

String.Join符連接使用每個元件之間的指定的分隔的一個字符串數組中的所有元素。 這裏的分隔符是「,」。

相關問題