简体   繁体   中英

Dynamically adding XElements to XAttribute using C#

<?xml version="1.0" encoding="ISO-8859-1"?>
<servers>  
  <server serverid="server1" asset="Sample" >
    <port portid ="port1" asset="Sample"  ></port>  
    <port portid ="port2" asset="Sample"  ></port>      
  </server>

  <server serverid="server2" asset="Sample" >
    <port portid ="port1" asset="Sample"  ></port> 
    <port portid ="port2" asset="Sample"  ></port>    
    <port portid ="port3" asset="Sample"  ></port>
    <port portid ="port4" asset="Sample"  ></port>        
  </server>
<server serverid="server1" asset="Sample" >
    <port portid ="port1" asset="Sample"  ></port> 
    <port portid ="port2" asset="Sample"  ></port>    
    <port portid ="port3" asset="Sample"  ></port>   
  </server>

</servers>  

I am trying to add Server XElements and port XElements to the existing XML DOC. I tried by using for & forEach to add port Xelements to server Xelement. The trick here is the count of port XElemnts vary from server to server. Please help me out of this. The following is the sample code, I have tried.

var xdoc = XDocument.Load("C:\\sample.xml");
             var server = new XElement("server",
                 new XAttribute("serverid", ServerId),
                 new XAttribute("name", ServerName),
                 (foreach(var sample in test)
                 {
                 new XElement("port",
                     new XAttribute("asset", PortName),
                     new XAttribute("portid", PortId));
                 });

It's strange that you are not using sample variable in a loop. But if you want to add new port element for each item in test collection, then you should project each item to XElement and return collection of these elements:

 var fileName = @"C:\sample.xml";
 var xdoc = XDocument.Load(fileName);

 var server = 
     new XElement("server",
         new XAttribute("serverid", ServerId),
         new XAttribute("name", ServerName),
             test.Select(sample =>
                 new XElement("port",
                     new XAttribute("asset", PortName),
                     new XAttribute("portid", PortId)
                 ))
         );

Keep in mind, that foreach loop does not return anything. But you need to provide value to server element you are creating.

 xdoc.Root.Add(server);
 xdoc.Save(fileName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM