【问题标题】:How to change the content of elements and attributes如何更改元素和属性的内容
【发布时间】:2010-11-27 21:20:53
【问题描述】:

我发现很多使用 XmlNodeList 的例子,但遗憾的是 WP7 不支持这个,所以我有点难过。

我有一个看起来有点像这样的 XML 文档

<users>
    <user id="50">
        <username>testuser</username>
    </user>
</users>

我需要能够将用户 ID 更改为另一个值并允许更改用户名。

例如,我还希望能够删除用户 ID 为 50 的元素。

非常感谢任何帮助!

谢谢

【问题讨论】:

    标签: c# xml silverlight linq windows-phone-7


    【解决方案1】:

    这里有一些不同的技术,都使用 Xlinq(并在 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");
        }                
    }
    

    【讨论】:

      【解决方案2】:

      使用 LINQ to XML。

      System.Xml.Linq 添加到您的参考文献中。

      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();
          }
      }
      

      【讨论】:

      • 感谢您的快速回复,但它引发了错误:'System.Xml.Linq.XNode' does not contain a definition for 'Attribute' and no extension method 'Attribute' accepting a first argument of type 'System.Xml.Linq.XNode' could be found 我的参考文献中已有 System.Xml.Linq。
      • 对 Silverlight 使用 XAttribute
      猜你喜欢
      • 2021-08-03
      • 2019-07-26
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 2017-05-06
      • 2011-05-03
      • 1970-01-01
      相关资源
      最近更新 更多