如何更改xml字符串中的值?

时间:2016-03-16 13:09:48

标签: c# xml xml-parsing

我有以下方法

string UpdateXmlString(string xmlString) {...}

我想查找名称中包含password的所有标记并删除值;

在:

<job xmlns:i=\"...\" xmlns=\"...">
<password>asdfasdf</password>
<adminPassword>asd</adminPassword>
...</job>

预期结果:

<job xmlns:i=\"..." xmlns=\"...">
<password></password>
<adminPassword></adminPassword>
...</job>

如何实施此方法?

3 个答案:

答案 0 :(得分:1)

您应该只使用XmlDocument或XDocument来解析它。我不会手动操作XML字符串。

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

namespace XDocumentTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                String xml = "<?xml version=\"1.0\"?><rootElement>";
                xml += "<user id=\"1\"><password>temp</password></user>";
                xml += "<user id=\"2\"><adminPassword>foobar</adminPassword></user>";
                xml += "<user id=\"3\"><somePassWORDelement>foobarXYZ</somePassWORDelement></user>";
                xml += "</rootElement>";
                XDocument doc = XDocument.Parse(xml);
                foreach (XElement element in doc.Descendants().Where(
                    e => e.Name.ToString().ToLower().Contains("password")))
                {
                    Console.WriteLine(element);
                    // Delete your value here. Either changing the text node
                    // or by removing the password node. E.g.

                    element.Value = string.Empty;
                }

                Console.WriteLine(doc.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            while (Console.ReadKey(true).Key != ConsoleKey.Escape)
            {
            }
        }
    }
}

答案 1 :(得分:0)

您应该使用XPathNavigator。

在MSDN中有一些示例可以帮助您: https://msdn.microsoft.com/en-us/library/zx28tfx1(v=vs.110).aspx

答案 2 :(得分:0)

var doc = XDocument.Load(path); 

var element = doc.Descendants("YOUR_Descendants")
                    .Where(arg => arg.Attribute("ExampleID").Value == "3" )// 
                    .Single();

element.Element("UpdateElements")
    .Element("UpdateElements_fc").Value = "222";// update
                doc.Save(path); //save