2011-01-07 84 views
1

我有這樣的:如何將元素添加到XML文檔?

<dockmenu>  
<photo image="images/4runner-sr5.jpg" url="www.example.com" target="_blank"><![CDATA[4Runner]]></photo>  
<photo image="images/4runner.jpg" url="www.example.com" target="_blank"><![CDATA[4Runner<br>Dock Beautiful]]></photo>  
</dockmenu> 

,我需要一個多元素添加到不同的信息使用(C#及ASP.net)的XML 所以它看起來就像這樣:

<dockmenu> 
<photo image="images/4runner-sr5.jpg" url="www.example.com" target="_blank"><![CDATA[4Runner]]></photo>  
<photo image="images/4runner.jpg" url="www.example.com" target="_blank"><![CDATA[4Runner<br>Dock Beautiful]]></photo>  
<photo image="images/new.jpg" url="www.new.com" target="_blank"><![CDATA[New]]></photo>  
</dockmenu> 

我該怎麼做呢?

+0

您需要澄清的問題一點點,你的前後是完全一樣的,並沒有一個正確的XML – MrEyes 2011-01-07 01:09:21

+0

這是什麼都與C#或ASP.NET做? – 2011-01-07 01:30:01

回答

2

的LINQ to XML:

var text = @"<dockmenu>  
<photo image=""images/4runner-sr5.jpg"" url=""www.example.com"" target=""_blank""><![CDATA[4Runner]]></photo>  
<photo image=""images/4runner.jpg"" url=""www.example.com"" target=""_blank""><![CDATA[4Runner<br>Dock Beautiful]]></photo>  
</dockmenu>"; 
var dockMenu= XElement.Parse(text); 
var photo = new XElement("photo"); 
photo.SetAttributeValue("image", "images/new.jpg"); 
photo.SetAttributeValue("url", "www.new.com"); 
photo.SetAttributeValue("target", "_blank"); 
photo.Add(new XCData("New")); 
dockMenu.Add(photo); 
var newText = dockMenu.ToString(); 

或者,更簡潔的版本:

​​
0

您也可以直接節點添加到DOM。

XmlDocument doc = new XmlDocument(); 
var text = @"<dockmenu>  
       <photo image=""images/4runner-sr5.jpg"" url=""www.example.com"" target=""_blank""><![CDATA[4Runner]]></photo>  
       <photo image=""images/4runner.jpg"" url=""www.example.com"" target=""_blank""><![CDATA[4Runner<br>Dock Beautiful]]></photo>  
      </dockmenu>"; 
doc.LoadXML(text); 
XmlNode newChild = doc.CreateElement("photo"); 
XmlAttribute image = doc.CreateAttribute("image"); 
image.Value = "images/new.jpg"; 
newChild.Attributes.Append(image); 

XmlAttribute url = doc.CreateAttribute("url"); 
url.Value = "www.new.com"; 
newChild.Attributes.Append(url); 

XmlAttribute target = doc.CreateAttribute("target"); 
target.Value = "_blank"; 
newChild.Attributes.Append(target); 

XmlNode root = doc.SelectSingleNode("//dockmenu"); 
root.AppendChild(newChild);