2015-10-03 43 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符连接使用每个元件之间的指定的分隔的一个字符串数组中的所有元素。 这里的分隔符是“,”。

相关问题