How to change XML element value - c#

I need your help to finish my task also gain some knowledge from it.
I am having XMl like below
<?xml version="1.0" encoding="UTF-8"?>
<spml:batchRequest xmlns:subscriber="urn:abc:names:prov:gw:SUBSCRIBER:3:0" xmlns:spml="urn:abc:names:prov:gw:SPML:2:0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" execution="synchronous" timestamp="true" processing="sequential" onError="exit_commit">
<version>SUBSCRIBER_v30</version>
<request xsi:type="spml:ModifyRequest" returnResultingObject="full">
<version>SUBSCRIBER_v30</version>
<objectclass>Subscriber</objectclass>
<identifier>1234567890</identifier>
<modification name="udm5gData/servingPlmnId[#plmnId='20201']/provisionedData/sessionManagementSubscriptionData[#singleNssai='1-000002']/dnnConfiguration[#dnnId='dj.nmdd']" operation="remove" scope="uniqueTypeMapping" xmlns:subscriber="urn:abc:names:prov:gw:SUBSCRIBER:3:0">
</modification>
</request>
</spml:batchRequest>
Out of this I need to modify the #singleNssai='1-000002' from modification tag Could anyone help me to change.
Something like #singleNssai='2-000001'
I am trying like below
XmlDataDocument doc = new XmlDataDocument();
doc.Load("D:\\soaptemp\\test.xml");
XmlNode singlenssais =
doc.SelectSingleNode("//modification/name/#singleNssai");
if (singlenssais != null)
{
singlenssais.Value = "2-000001"; // Set to new value.
}

Using 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)
{
XDocument doc = XDocument.Load(FILENAME);
XElement modification = doc.Descendants("modification").First();
XAttribute name = modification.Attribute("name");
string strName = (string)name;
strName = strName.Replace("1-000002", "2-000001");
name.SetValue(strName);
}
}
}

Related

Remove XML Header and Footer nodes using c#

I have console app which i am trying to automate , there is manual process to remove headers and footer tags form .trg file . Can anyone suggest how to remove headers and footers using c sharp.
Header looks like this.
<Batch remotefolder="\\srv-dg-procl13\nexdox\nxtil04\process\200863-142325x-mkts\output\archive\absamples_pims_pdf\" grid="200863-142325X-MKTS" streamID="ABSAMPLES_PIMS_PDF" delivertobox="False">
<Application application="NXTIL04" name="Mifid 10 percent drop Notification " output="ABSAMPLES_PIMS_PDF">
<Indexes>
<Index name="Reference" description="Reference" type="StringDefinition" visible="True" />
</Indexes>
</Application>
footer looks like this .
</Batch>
This is what i am trying to do but not working .
private void RemoveHeader(string Xlfile)
{
XmlDocument doc = new XmlDocument();
doc.Load(Xlfile);
foreach (XmlNode node in doc.SelectSingleNode("Batch"))
{
doc.RemoveAll();
}
}
XPath is your friend here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace testconsole
{
class Program
{
public static string strFileName = "c:\\temp\\test.xml";
static void Main(string[] args) {
XmlDocument xml = new XmlDocument();
xml.Load(strFileName);
XmlElement ndMatch = (XmlElement)xml.SelectSingleNode("//Application");
if (ndMatch != null) {
XmlDocument xmlNew = new XmlDocument();
xmlNew.LoadXml(ndMatch.OuterXml);
xmlNew.Save(strFileName + ".new");
} else {
Console.Write("Cannot load " + strFileName);
}
}
}
}

XPath query with multiple namespaces

What do you think the correct XPath is to pull the dublin core identifier below?
I added a namespace manager with these entries:
// Add the namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(m_xml.NameTable);
nsmgr.AddNamespace("mets", "http://www.loc.gov/METS/");
nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
nsmgr.AddNamespace("dcterms", "http://purl.org/dc/terms/");
And I have tried 15 or so different XPath iterations including the ones below. When I do not get an error, the result is null.
//xml_uuid = m_xml.SelectSingleNode("/mets:mets/mets:dmdSec/mets:mdWrap/mets:xmlData/dcterms:dublincore/dc:identifier").Value;
xml_uuid = m_xml.SelectSingleNode("//dc:identifier",nsmgr).Value;
Here is the xml I am working with:
<mets:mets xmlns:mets="http://www.loc.gov/METS/" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/METS/ http://www.loc.gov/standards/mets/version18/mets.xsd">
<mets:metsHdr CREATEDATE="2017-03-08T20:13:27" />
<mets:dmdSec ID="dmdSec_1">
<mets:mdWrap MDTYPE="DC">
<mets:xmlData>
<dcterms:dublincore xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xsi:schemaLocation="http://purl.org/dc/terms/ http://dublincore.org/schemas/xmls/qdc/2008/02/11/dcterms.xsd">
<dc:identifier>F2015.5</dc:identifier>
</dcterms:dublincore>
</mets:xmlData>
</mets:mdWrap>
</mets:dmdSec>
etc...
I am trying to assign the dc:identifier - F2015.5 in this case - to a string.
With xml linq and ignoring the namespaces :
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication131
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string results = (string)doc.Descendants().Where(x => x.Name.LocalName == "identifier").FirstOrDefault();
}
}
}
Here is one working answer. I believe the main thing is to use .InnerText and not .Value.
xml_uuid = m_xml.SelectSingleNode("//mets:xmlData[1]/dcterms:dublincore[1]/dc:identifier[1]", nsmgr).InnerText;

Delete node with C# in XML

I'm Trying to Delete a node from XML with C#, but for some reason I can't.
What I doing wrong?
The code runs well, respond with true, but the XML don't change and the node is not eliminated.
This is my code to Delete:
internal static bool DeleteCamera(string name)
{
XmlDocument xml = new XmlDocument();
xml.Load("xmlpath.xml");
XmlNode toDelete = xml.SelectSingleNode("//Camera[#Name='" + name + "']");
if (toDelete == null)
{
return false;
}
else
{
toDelete.ParentNode.RemoveChild(toDelete);
xml.Save("xmlpath.xml");
return true;
}
}
This is my XML result with WCF service:
<Cameras>
<Camera Name="Camara1" Url="Camara1" Width="600" Height="800" />
<Camera Name="Camara2" Url="Camara2" Width="600" Height="800" />
</Cameras>
Thank you guys, the problem was the containing apostrophe (?) before and after name string.
XmlNode toDelete = xml.SelectSingleNode("//Camera[#Name='" +name+ "']");
But I don't know why I need to restart the service to see the changes if I have a Method to load the xml file.
Use xml linq. The name in xml is "Camara1" not "Camera1".
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);
string removeName = "Camara1";
XElement camera = doc.Descendants().Where(x => (x.Name.LocalName == "Camera") && ((string)x.Attribute("Name") == removeName)).FirstOrDefault();
camera.Remove();
}
}
}

Using c# to read XML that has nested namespaces

I am trying to extract the following values from this XML using C#.
Messages - the inntertext
success="true" - just the "true" bit
status="Released" - just the "Released" bit
Namespaces are clearly the issue here - but I can't get it right.
Can someone provide an example of parsing this file here please?
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<tns:executeCreateLoanIncreaseResponse xmlns:tns="http://api.ws.liq.pisys.com/">
<CreateLoanIncreaseResponse success="true">
<OutstandingTransactionAsReturnValue version="1.0" alias="LIBRLC" status="Released" id="5CJB6GS"></OutstandingTransactionAsReturnValue>
<Messages>
<Message>CreateLoanIncrease>>Effective date current business date (08-Sep-2016).</Message>
<Message>CreateLoanIncrease>>Intent Notices have not been generated.</Message>
<Message>CreateLoanIncrease>>You are about to release this increase.</Message>
</Messages>
</CreateLoanIncreaseResponse>
</tns:executeCreateLoanIncreaseResponse>
</soapenv:Body>
</soapenv:Envelope>
Try 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);
XElement messages = doc.Descendants().Where(x => x.Name.LocalName == "Messages").FirstOrDefault();
XNamespace ns = messages.GetDefaultNamespace();
List<string> strMessages = messages.Elements(ns + "Message").Select(x => (string)x).ToList();
}
}
}
You can use Linq2Xml and XPath
var xDoc = XDocument.Load(filename);
var success = (bool)xDoc.XPathSelectElement("//CreateLoanIncreaseResponse").Attribute("success");
var status = (string)xDoc.XPathSelectElement("//OutstandingTransactionAsReturnValue").Attribute("status");
var messages = xDoc.XPathSelectElements("//Message").Select(x => (string)x.Value).ToList();

C# & LINQ - Get names of parent elements in xml query

I have an XML file with IP addresses and their assigned locations/floors that looks like this:
<Locations>
<LOCATION1>
<FLOOR1>
<SECTION1>
<IP>10.10.10.10</IP>
<IP>etc....
</SECTION1>
</FLOOR1>
</LOCATION1>
.....
What I am attempting to do is get query for an IP address and return the names of the parent elements. I am able to query for that IP but I have not had any luck figuring out how to get the parent elements names (i.e. SECTION1, FLOOR1, LOCATION1). Here is the code I am using for querying xml to find the IP, I just have it returning the value at the moment to verify my query was successful:
var query = from t in xmlLocation.Descendants("IP")
where t.Value.Equals(sIP)
select t.Value;
Try this :
XML
<?xml version="1.0" encoding="utf-8" ?>
<Locations>
<LOCATION1>
<FLOOR1>
<SECTION1>
<IP>10.10.10.10</IP>
<IP>20.20.20.20</IP>
</SECTION1>
</FLOOR1>
<FLOOR2>
<SECTION1>
<IP>30.30.30.30</IP>
<IP>40.40.40.40</IP>
</SECTION1>
</FLOOR2>
</LOCATION1>
</Locations >
​
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
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);
var results = doc.Descendants("LOCATION1").Elements().Select(x => new
{
parent = x.Name.ToString(),
ip = x.Descendants("IP").Select(y => (string)y).ToList()
}).ToList();
}
}
}
​
The code below gets location, floor, and section
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
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);
var results = doc.Descendants("Locations").Elements().Select(x => x.Elements().Select(y => y.Elements().Select(z => new {
location = x.Name.ToString(),
floor = y.Name.ToString(),
section = z.Name.ToString(),
ip = z.Descendants("IP").Select(i => (string)i).ToList()
})).SelectMany(a => a)).SelectMany(b => b).ToList();
}
}
}
​
var xDoc = XDocument.Load(filename);
var ip = xDoc.XPathSelectElement("//IP['10.10.10.10']");
var names = ip.Ancestors().Select(a => a.Name.LocalName).ToList();
names will contain SECTION1, FLOOR1, LOCATION1, Locations
If you know those name beforehand you can also use them to select the correct node
var ip = xDoc.XPathSelectElement("//LOCATION1/FLOOR1/SECTION1/IP['10.10.10.10']");
or
var section = xDoc.XPathSelectElement("//LOCATION1/FLOOR1/SECTION1[IP['10.10.10.10']]");

Categories

Resources