I have this:
<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>
And I need to add one more element to the xml with different information using(C# and ASP.net) so it will look like this:
<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>
开发者_如何学编程
How do I do this?
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();
Or, for a more concise version:
var dockMenu= XElement.Parse(text);
dockMenu.Add(
new XElement("photo",
new XAttribute("image", "images/new.jpg"),
new XAttribute("url", "www.new.com"),
new XAttribute("target", "_blank"),
new XCData("New")));
var newText = dockMenu.ToString();
You can also add nodes to the DOM directly.
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);
精彩评论