如何使用C#更新XML中的节点值

时间:2017-01-09 20:54:57

标签: c# xml visual-studio-2008 ssis

我必须使用修改后的值更新原始XML文件。下面是我的示例XML文件:

<request>
<facility>
<alternateIDs>
            <alternateID code="ALT8">11111111</alternateID>
            <alternateID code="ALT12">111111111</alternateID>
            <alternateID code="ALT">1111111111</alternateID>
            <alternateID code="ALT1">11111111</alternateID>
            <alternateID code="ALT9">11111111</alternateID>
            <alternateID code="ALT3">111111111</alternateID>
</alternateIDs>
</facility>
</request>

现在我想查找alternateID code="ALT"并将其值更改为00000000。我的最终文件应如下所示:

<request>
<facility>
<alternateIDs>
            <alternateID code="ALT8">11111111</alternateID>
            <alternateID code="ALT12">111111111</alternateID>
            <alternateID code="ALT">00000000</alternateID>
            <alternateID code="ALT1">11111111</alternateID>
            <alternateID code="ALT9">11111111</alternateID>
            <alternateID code="ALT3">111111111</alternateID>
</alternateIDs>
</facility>
</request>

如何使用XElementXAttributes实现此目的?我不熟悉XML和C#。任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:1)

知道了!

public static void ReplaceCode()
     {
        var root = new XmlDocument();
         root.Load(@"C:\data.xml");

        foreach (XmlNode e in root.GetElementsByTagName("alternateID"))
        {
            if (e.Attributes["code"].Value.Equals("ALT"))
            {
                e.FirstChild.Value = "00000000"; // FirstChild because the inner node is actually the inner text, yeah XmlNode is weird.
                break;
            }
        }
        root.Save(@"C:\data.xml");
    }

向我提出任何相关信息,我可以澄清一下。 :)

答案 1 :(得分:0)

试试这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication34
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement alt = doc.Descendants("alternateID").Where(x => (string)x.Attribute("code") == "ALT").FirstOrDefault();
            alt.Value = "00000000";

        }


    }


}

答案 2 :(得分:0)

这是一种非Linq的方式,虽然linq如果你知道如何阅读它会更清洁。

import {Component} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";

@Component({
  templateUrl: "app/components/login/login.html"
})
export class LoginComponent {

  constructor(public route: ActivatedRoute, public router: Router) { }

  loginSuccessful() {
    let redirect = this.route.snapshot.queryParams['redirect'];
    let redirectUrl = redirect != null ? redirect : '/dashboard/';
    console.log('redirect to: ' + redirect);
    this.router.navigate([redirectUrl]);
  }

}