How to change value in xml string? - c#

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?

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)
{
}
}
}
}

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

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

Related

Getting values of both attribute and element in an xml

I have the following xml
<lists>
<list Group="3">More_lists_go_here</list>
</lists>
What I want is both the list element value which is More_lists_go_here and the Group attribute value which is 3.
What I have tried so far is
XmlDocument doc = new XmlDocument();
doc.LoadXml("<list Group=\"3\">More_lists_go_here</list>");
XmlElement root = doc.DocumentElement;
string value = root.Descendants("lists").Elements("list").Select(x => (string)x.Attribute("Group")).ToList();
what that gets me is
value = 3
what I want is both 3 and More_lists_go_here for string value
Use xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication40
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string input = "<lists><list Group=\"3\">More_lists_go_here</list></lists>";
XDocument doc = XDocument.Parse(input);
var results = doc.Descendants("list").Select(x => new { group = (string)x.Attribute("Group"), value = (string)x }).ToList();
}
}
}

Convert XML to formatted plain text issue

I have the following XML and i want to convert the contents to something along the lines of the following format.
PatientId: 123455, IdScheme: Test ....
<?xml version="1.0"?>
<gls:TheDocument xmlns:pbr="http://www.something.com"
xmlns:gls="http://www.testsomething.com"
xmlns:cnr="http://www.organisation.com"
xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" schemaVersion="2.8">
<gls:PatientDem>
<cnr:PatientId>
<cnr:IdValue>123455</cnr:IdValue>
<cnr:IdScheme>TEST</cnr:IdScheme>
<cnr:IdType>PRN</cnr:IdType>
</cnr:PatientId>
<cnr:PatientName>
<cnr:Name>
<cnr:Title>Mr</cnr:Title>
<cnr:GivenName>Joe</cnr:GivenName>
<cnr:FamilyName>Wood</cnr:FamilyName>
</cnr:Name>
<cnr:NameType>Current Name</cnr:NameType>
</cnr:PatientName>
<cnr:PatientAddress>
<cnr:Address>
<cnr:AddressLine>57 High Street</cnr:AddressLine>
<cnr:AddressLine>London</cnr:AddressLine>
</cnr:Address>
<cnr:PostCode>WC1E 7HU</cnr:PostCode>
<cnr:AddressType>Current Residence</cnr:AddressType>
</cnr:PatientAddress>
<cnr:DateOfBirth>1969-11-02</cnr:DateOfBirth>
<cnr:Sex>M</cnr:Sex>
</gls:PatientDem>
<pbr:PatientAdminRef>
<pbr:Referrer>
<pbr:RefGP>
<cnr:GpcpName>
<cnr:FullName>DR SMITH</cnr:FullName>
</cnr:GpcpName>
<cnr:TheOrganisation>
<cnr:OrganisationId>
<cnr:IdValue>52522</cnr:IdValue>
<cnr:IdScheme>PracticeID</cnr:IdScheme>
<cnr:IdType>Healthcare Organisation</cnr:IdType>
</cnr:OrganisationId>
<cnr:OrganisationName>National Health
Service</cnr:OrganisationName>
<cnr:OrganisationAddress>
<cnr:TheAddress>
<cnr:AddressLine1>Centre House</cnr:AddressLine1>
<cnr:AddressLine2>799 Chichester
Street</cnr:AddressLine2>
<cnr:AddressLine3>London</cnr:AddressLine3>
</cnr:TheAddress>
<cnr:AddressType>Practice Address</cnr:AddressType>
</cnr:OrganisationAddress>
<cnr:OrganisationTelecom>
<cnr:TelephoneNumber>016190542350</cnr:TelephoneNumber>
<cnr:TeleType>Voice</cnr:TeleType>
</cnr:OrganisationTelecom>
</cnr:TheOrganisation>
</pbr:RefGP>
</pbr:Referrer>
</pbr:PatientAdminRef>
</gls:TheDocument>
So is it possible to do this? I had a go at doing this but I know for a fact i am doing it wrong as it cannot produce the result i want so any help will be much appreciated:
C# Code
XDocument doc = XDocument.Parse(xml);
XElement root = doc.Root;
XNamespace glsNs = root.GetNamespaceOfPrefix("gls");
XNamespace cnrNS = root.GetNamespaceOfPrefix("cnr");
XNamespace pbrNS = root.GetNamespaceOfPrefix("pbr");
var output = new StringBuilder();
foreach (var result in doc.Descendants(gls + "PatientDem").Select(x => new {
Key = (string)x.Name.LocalName,
Value = x.Value
}))
{
output.AppendLine($"{result.key} : {result.value}");
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication108
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
XNamespace cnrNs = root.GetNamespaceOfPrefix("cnr");
var results = doc.Descendants(cnrNs + "PatientId").Select(x => new {
value = (string)x.Element(cnrNs + "IdValue"),
scheme = (string)x.Element(cnrNs + "IdScheme")
}).ToList();
}
}
}

Grab xml value using XmlDocument

I want to grab UPC value from the following XML example node, but the current doc.SelectNodes fails to grab that value. I am using XmlDocument to process my XML. Can you fix my code to grab UPC value? What am I doing wrong here?
C# Code:
string responseStr = new StreamReader(responseStream).ReadToEnd();
responseStream.Flush();
responseStream.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseStr);
if (doc.GetElementsByTagName("Ack").Item(0).InnerText != "Failure")
{
string UPC = doc.SelectNodes("Item").Item(0).SelectNodes("UPC").Item(0).InnerText;
}
XML Sample:
<?xml version="1.0" encoding="UTF-8"?>
<GetItemResponse xmlns="urn:ebay:apis:eBLBaseComponents">
<Timestamp>2018-07-28T08:18:10.048Z</Timestamp>
<Ack>Success</Ack>
<Version>1069</Version>
<Build>E1069_CORE_API_18748854_R1</Build>
<Item>
<ProductListingDetails>
<ISBN>Not Applicable</ISBN>
<UPC>853365007036</UPC>
<EAN>0853365007036</EAN>
<BrandMPN>
<Brand>UpCart</Brand>
<MPN>MPCB-1DX</MPN>
</BrandMPN>
<IncludeeBayProductDetails>true</IncludeeBayProductDetails>
</ProductListingDetails>
</Item>
</GetItemResponse>
You have a namespace that must be used to get values. Here is the easy way using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XNamespace ns = doc.Root.GetDefaultNamespace();
string UPC = (string)doc.Descendants(ns + "UPC").FirstOrDefault();
}
}
}
If you have nulls use this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XNamespace ns = doc.Root.GetDefaultNamespace();
var upcs = doc.Descendants(ns + "UPC");
if (upcs != null)
{
string upc = (string)upcs.FirstOrDefault();
}
}
}
}

"The given path's format is not supported" Error when trying to pull XML into Treeview

Currently trying to get a XML file from a location on my machine to display to my Treeview. I pretty much used the code from another stackoverflow question:
Recursion, parsing xml file with attributes into treeview c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string Path = Application.StartupPath + #"C:\Users\apearson\Documents\Works.xml";
public Form1()
{
InitializeComponent();
DisplayTreeView(Path);
}
private void DisplayTreeView(string pathName)
{
try
{
XmlDocument dom = new XmlDocument();
dom.Load(pathName);
treeView1.Nodes.Clear();
foreach (XmlNode xNode in dom.ChildNodes)
{
var tNode = treeView1.Nodes[treeView1.Nodes.Add(new TreeNode(xNode.Name))];
AddNode(xNode, tNode);
}
}
catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
{
if (inXmlNode is XmlElement)
{
foreach (var att in inXmlNode.Attributes.Cast<XmlAttribute>().Where(a => !a.IsDefaultNamespaceDeclaration()))
{
inTreeNode.Text = inTreeNode.Text + " " + att.Name + ": " + att.Value;
}
var nodeList = inXmlNode.ChildNodes;
foreach (XmlNode xNode in inXmlNode.ChildNodes)
{
var tNode = inTreeNode.Nodes[inTreeNode.Nodes.Add(new TreeNode(xNode.Name))];
AddNode(xNode, tNode);
}
}
else
{
inTreeNode.Text = (inXmlNode.OuterXml).Trim();
}
treeView1.ExpandAll();
}
}
When debugging, I noticed that it will stop at the dom.Load(pathName) then go straight to the catch. Then throw me the error of "The given path's format is not supported". I've seen some other articles with this issue but nothing with a Treeview so don't know if they would have been much help. Is there something I'm missing?
This part
string Path = Application.StartupPath + #"C:\Users\apearson\Documents\Works.xml
... will concatenate the startup path with the full path you define as literal.
This will lead to something like
C:\blah\blub\C:\Users\apearson\Documents\Works.xml
...which is not a valid path..

Get value from simple XML document

I have the following XML
<User
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/GaryLeaderboardsAPI.Models">
<Game_ID>3</Game_ID>
<UserGUID>e00d3560-4133-4ba6-8bba-e6c8659468b4</UserGUID>
<UserName>tony2</UserName>
<User_ID>16</User_ID>
</User>
Using C# I am loading this into an XMLDocument, How do I retrieve the UserGUID value?
Leveraging System.Xml.Linq you could do
string xml = "..."; // your inline XML
var doc = System.Xml.Linq.XDocument.Parse(xml);
or
string xmlFile = "..."; // your XML filename
var doc = System.Xml.Linq.XDocument.Load(xmlFile);
and then, to get the UserGUID
var userGuid = doc.Descendants().Where(x=>x.Name.LocalName == "UserGUID").First().Value;
This will work for you.
string xml = "<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/GaryLeaderboardsAPI.Models\">" +
"<Game_ID>3</Game_ID>" +
"<UserGUID>e00d3560-4133-4ba6-8bba-e6c8659468b4</UserGUID>" +
"<UserName>tony2</UserName>" +
"<User_ID>16</User_ID>" +
"</User>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var id = doc.GetElementsByTagName("UserGUID")[0].InnerText;
You need to use the namespace. I often use mipnw approach (probably stole idea from one of my postings). See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement user = doc.Root;
XNamespace ns = user.GetDefaultNamespace();
string UserGUID = (string)user.Element(ns + "UserGUID");
}
}
}

Categories