Reputation:
I have the following method
string UpdateXmlString(string xmlString) {...}
I would like to find all tags which name contain password
and delete a value;
Before:
<job xmlns:i=\"...\" xmlns=\"...">
<password>asdfasdf</password>
<adminPassword>asd</adminPassword>
...</job>
Expected result:
<job xmlns:i=\"..." xmlns=\"...">
<password></password>
<adminPassword></adminPassword>
...</job>
How to implement this method?
Upvotes: 2
Views: 6567
Reputation: 6473
You should simply be using XmlDocument or XDocument to parse this. I wouldn't manipulate XML strings manually.
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)
{
}
}
}
}
Upvotes: 3
Reputation: 118
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
Upvotes: 0
Reputation: 36103
You should use XPathNavigator.
In MSDN are some examples that will help you: https://msdn.microsoft.com/en-us/library/zx28tfx1(v=vs.110).aspx
Upvotes: 0