开发者

How to change the content of elements and attributes

I have found lots of examples of this using XmlNodeList but sadly WP7 does not support this so im a bit stumped.

I have an XML document which looks a bit like this

<users>
    <user id="50">
        <username>testuser</username>
    </u开发者_如何学JAVAser>
</users>

I need to be able to change the user id to another value and also allow the username to be changed.

I would also like to be able to remove the element with the user id of 50 for example.

Any help is very much appreiciated!

Thanks


Here's a few different techniques, all using XLinq (and tested on WP7):

string usersXml = @"<users><user id=""50""><username>testuser</username></user><user id=""51""><username>jamie_user</username></user></users>";

XElement doc = XElement.Parse(usersXml);

// LINQ query syntax for find and removal
// Add reference to System.Xml.Linq and add using System.Xml.Linq and using System.Linq
var matchingUsers = from user in doc.Elements("user")
                    where (string)user.Attribute("id") == "50"
                    select user;
// remvoing the users
matchingUsers.Remove();

// another way to find the users...
doc = XElement.Parse(usersXml); // reload for demo
var matchingUsers2 = doc.Elements("user").Select(
    xUser => (string)xUser.Attribute("id") == "50");

// change the name
doc = XElement.Parse(usersXml); // reload for demo
matchingUsers = from user in doc.Elements("user")
                where (string)user.Attribute("id") == "50"
                select user;

// replacing the name ...
foreach (var user in matchingUsers)
{
    var usernameElement = user.Element("username");
    if (usernameElement != null) {
        usernameElement.SetValue("newUserName");
    }                
}


Use LINQ to XML.

Add System.Xml.Linq to your references.

XElement users = XElement.Load("{file}");

foreach (var user in users.Nodes()) 
{
    if(user.Attribute("id") == 50)
    {
         user.Attribute("id") = 10;
         user.Descendant("username") == "new User";
         //Or remove like this:
         user.Remove();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜