0

I am trying to delete/Scrub few elements from the xml using c# with the help of xpaths. I am trying to replace the value of social_security_number with "Scrubbed" in both the child tags named "Customers". But my program is landing in many errors. Please correct me.

xml :

<?xml version="1.0" encoding="utf-16"?>
<LoanApplications xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="12345" bundle_id="12225" version="1.0">
    <LoanApplication payment_call="False" version="1.0" app_status="I" perform_dupe_check="1"   bundle_id="12225"  UpdateReviewed="True">
            <Customers id = "12" name =  "krish" ssn = "123456789">
    </LoanApplication>      
    <LoanApplication deal_type="RESPONSE"  payment_call="True" version="1.0"  app_status="I" perform_dupe_check="1"   bundle_id="12225"  UpdateReviewed="True">
    <Customers id = "12" name =  "krish" ssn = "123456789">
    </LoanApplication>
</LoanApplications>

Program :

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            XmlDocument doc = new XmlDocument();
            doc.Load("mytestfile.xml");
            doc.SelectSingleNode("/LoanApplications/LoanApplication[@deal_type="%DealTypeALL%"]/LoanApplicationStates/LoanApplicationState/Customers/Customer[@customer_id="%CustIDALL%"]/").Attributes["social_security_number"].InnerText = "Scrubbed";

            doc.Save("mytestfile.xml");

        }
    }
}
0

3 Answers 3

0
var doc = XDocument.Parse(System.IO.File.ReadAllText("C:\\Users\\jason\\Desktop\\Input\\2015\\09\\03\\mytestfile.xml"));
foreach (var customer in doc.Descendants("Customer"))
{
    var ssn = customer.Attribute("social_security_number");
    if (ssn != null)
    {
        ssn.Value = "scrubbed";
    }
}

doc.Save("file.xml");
14
  • It is resulting error in line doc.Load("mytestfile.xml"); cannot use local variable 'doc' before it is declared. May 9, 2016 at 19:42
  • This is the error I am getting : A first chance exception of type 'System.Xml.XmlException' occurred in System.Xml.dll Additional information: There is no Unicode byte order mark. Cannot switch to Unicode. May 9, 2016 at 19:51
  • var doc = XDocument.Load("C:\\Users\\jason\\Desktop\\Input\\2015\\09\\03\\mytestfile.xml"); This is my input string May 9, 2016 at 19:52
  • Your XML is not correctly formatted, make sure the "Customers" tag is closed. I had to fix it in order to test. Notice the "/>" in the end here <Customers id = "12" name = "krish" ssn = "123456789" />
    – SirH
    May 9, 2016 at 19:52
  • Is it because the customer is a descendant of LoanApplication ? And the LoanApplication Node is differentiated using deal type = 'Recommended' or 'Requested' May 9, 2016 at 19:55
0

You have few needed nodes instead of one. Thus, you should use SelectNodes instead of SelectSingleNode method.

var doc = new XmlDocument();
doc.Load("mytestfile.xml");

var ssns = doc.SelectNodes("LoanApplications/LoanApplication/LoanApplicationStates/LoanApplicationState/Customers/Customer/@social_security_number");

foreach (XmlAttribute ssn in ssns)
    ssn.InnerText = "Scrubbed";

doc.Save("mytestfile.xml");

You can use shorter XPath with descendants. But it has less performance.

var ssns = doc.SelectNodes("//Customer/@social_security_number");
5
  • I am getting error at doc.Load("C:\\Users\\spechetti\\Desktop\\Input\\2015\\09\\03\\20150903143222.28405_Always_1441305129727.xml"); May 9, 2016 at 21:30
  • Error is : An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll Additional information: There is no Unicode byte order mark. Cannot switch to Unicode. May 9, 2016 at 21:30
  • @HadoopAddict - Probably you have invalid xml. Fix your xml. May 9, 2016 at 21:45
  • The problem is with the first line <?xml version="1.0" encoding="utf-16"?> If I change it to <?xml version="1.0"?> your code is working. But there are 1000s of files like these , is there any work around to make it work for the way it is now ? May 10, 2016 at 1:51
  • @HadoopAddict - I repeat: your xml is invalid. Where did you get it? I think it is saved in another encoding than utf-16. To avoid this, do not use simple text editors like Notepad to create and edit xml. Use specialized xml editors. May 10, 2016 at 9:14
0

This is real easy with xml linq

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

            List<XElement> ss = doc.Descendants().Where(x => x.Attribute("social_security_number") != null).ToList();
            foreach (XElement s in ss)
            {
                s.Attribute("social_security_number").Value = "Scrubbed";
            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.