delete specific child from xml document - c#

i have an xml file that as shown below
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfEtiquette xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Etiquette>
<BgColor>#8075D1C5</BgColor>
<BorderColor>#FF4E5B6F</BorderColor>
<AssociatedAffaireId>
<string>d4689f33-5600-47fe-883d-efcbf5e469c2</string>
<string>203cc4a8-8c24-4a2d-837c-29c7c1f73007</string>
<string>1bae35dd-d501-4d87-bdd4-147fc0ba29d2</string>
</AssociatedAffaireId>
<Label>Ouverte</Label>
</Etiquette>
</ArrayOfEtiquette>
I need to delete only
<string>203cc4a8-8c24-4a2d-837c-29c7c1f73007</string>
this is the code i tried, but its not working,
XDocument xmlSettings = XDocument.Load(chemin + "\\Etiquettes.xml");
if(xmlSettings.ToString().Contains(aff.Id))
{
string newXmlSettings = xmlSettings.ToString().Replace("<string>" +
aff.Id+ "</string>","");
}
xmlSettings.Save(chemin + "\\Etiquettes.xml");
Regards.

You can try with LINQ
//load the xml
var xdoc = XDocument.Load(filePath);
//find and remove
xdoc.Descendants("string")
.Where(x => x.Value == "203cc4a8-8c24-4a2d-837c-29c7c1f73007")
.Remove();
//save it back
xdoc.Save(filePath);

Related

Removing parentnode but not childnodes XmlElement

I'm in a situation where i need to get rid of my parentnode, but not my childnodes.
Here is how it loooks:
<?xml version="1.0" encoding="utf-8"?>
<ns0:MisMessage>
<mislife>
<party/>
<datetime>2018-06-04T09:35:33</datetime>
<insurance">
<number>123</number>
<amount>3</amount>
<indicator></indicator>
<text>asd</text>
</insurance>
</mislife>
<ns0:Message/>
</ns0:MisMessage>
And here is how i want it to look after i'm done.
<mislife>
<party/>
<datetime>2018-06-04T09:35:33</datetime>
<insurance">
<number>123</number>
<amount>3</amount>
<indicator></indicator>
<text>asd</text>
</insurance>
</mislife>
Is there any easy way to do this? I have tried and tried and tried. I have been looking all over the internet and i can't find out how to do it. The thing i want to remove will always be named ns0: in the beggning. Can i do it by removeing with substrings? THANKS!
I solved it like below, i converted the XMLDocument to XDocument and then used the descendants. Just like #bommelding showed in his example. Thank you all!
var xDocument = ToXDocument(xmlDocument);
if (xDocument != null)
{
var mislife = xDocument.Descendants("mislife").FirstOrDefault();
if (mislife != null)
{
return mislife;
}
}
public static XDocument ToXDocument(XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
XDocument doc = XDocument.Load(fileName);
XElement data = doc
.Descendants("mislife") // find your target
.Single(); // be brave, there should be exactly 1
data.Save(otherFileName); // saves with document <? ... ?>
Simple way with Linq (remember to add using System.Xml.Linq;):
string testxml = #"
<?xml version=""1.0"" encoding=""UTF-8""?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
XDocument doc = XDocument.Parse(testxml).Descendants().First().Document;
doc will be your xml without the root element
XDocument can load from files with
XDocument.Load("path");
or read XML like I did with
Xml.Parse("<xml....>");
and have also other options.
Result is:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Extract data from xml string

Let's say I have an xml string:
<?xml version="1.0" encoding="UTF-8"?>
<Return version="1.0">
<File>1</File>
<URL>2</URL>
<SourceUUID>1191CF90-5A32-4D29-9F90-24B2EXXXXXX0</SourceUUID>
</Return>
and I want to extract the value of SourceUUID, how?
I tried:
XDocument doc = XDocument.Parse(xmlString);
foreach (XElement element in doc.Descendants("SourceUUID"))
{
Console.WriteLine(element);
}
If all you want is the content of the SourceUUID element, and there's only going to be 1 in the XML, you can do this:
XDocument doc = XDocument.Parse(xmlString);
var value = doc.Descendants("SourceUUID").SingleOrDefault()?.Value;
If there are going to be more than one, you can do this:
var values = doc.Descendants("SourceUUID").Select(x => x.Value);
This gives you an enumerable of strings that are the text values of the elements.

Load data from XML nodes

i have this structure of data:
<?xml version="1.0" encoding="windows-1250"?>
<?xml-stylesheet type="text/xsl" href="usb71105.xsl"?>
<manas:usb xmlns:manas="http://www.manas.info/">
<manas:qr00>
<manas:verzemanas>26052708</manas:verzemanas>
<manas:verzexml>2016.03.29a</manas:verzexml>
<manas:druhtisku>U_Tisk2P/2159405/TRUE</manas:druhtisku>
</manas:qr00>
<manas:qr00>
<manas:verzemanas>26052710</manas:verzemanas>
<manas:verzexml>2016.03.30a</manas:verzexml>
<manas:druhtisku>U_Tisk2P/FALSE</manas:druhtisku>
</manas:qr00>
</manas:usb>
I need to save values of: manas:verzemanas ; manas:verzexml ;
I have this code:
XmlDocument doc = new XmlDocument();
doc.Load("d:\\83116623.XML");
foreach (XmlNode node in doc.DocumentElement)
{
string name = node.Attributes[0].ToString();
}
Have you any ideas please?
You're probably better off with XDocument. Also you need to use the namespace prefix. E.g.:
XNamespace ns = "http://www.manas.info/";
var xdoc = XDocument.Load(#"c:\temp\a\a.xml");
var verze = xdoc.Root.Elements(ns + "qr00")
.Elements(ns + "verzemanas")
.Select(e => e.Value);
verze.ToList().ForEach(v => Console.WriteLine(v));
prints
26052708
26052710

Duplicate existing element in xml in C#

Please I would like to clone element prijemkaItem from this xml:
The element prijemkaItem is got by this function:
XElement doc = XElement.Load("input.xml");
XmlReader reader = XmlReader.Create("input.xml");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name == "pri:prijemkaItem")
elementPrijemkaItem = XElement.ReadFrom(reader) as XElement;
break;
}
}
reader.Close()
I would like to put this element behind itself. Please any idea, how can I do this?
Thanks for any advice.
Assuming for simplicity that your Xml structure is the following:
<?xml version="1.0" encoding="utf-8"?>
<dat:dataPack xmlns:dat="datNamespace">
<dat:dataPackItem>
<pri:prijemka xmlns:pri="priNamespace">
<othernode></othernode>
</pri:prijemka>
</dat:dataPackItem>
</dat:dataPack>
If you want to duplicate the pri:prijemka node you can use Linq to Xml:
//using System.Xml.Linq;
//load the xml file
Document doc = XDocument.Load( "D:\\input.xml" );
//get the "dat" namespace
var datNamespace = doc.Root.GetNamespaceOfPrefix( "dat" );
//get "dat:dataPackItem" node
var dataPackItemNode = doc.Root.Element( datNamespace + "dataPackItem" );
//since you don't know the "pri" namespace you can do:
var prijemkaNode = dataPackItemNode.Descendants( )
.Where(x => x.Name.LocalName == "prijemka")
.FirstOrDefault();
//add it to the "dat:dataPackItem" node
dataPackItemNode.Add( prijemkaNode );
//save the xml file
doc.Save( "D:\\input.xml" );
The result is:
<?xml version="1.0" encoding="utf-8"?>
<dat:dataPack xmlns:dat="datNamespace">
<dat:dataPackItem>
<pri:prijemka xmlns:pri="priNamespace">
<othernode></othernode>
</pri:prijemka>
<pri:prijemka xmlns:pri="priNamespace">
<othernode></othernode>
</pri:prijemka>
</dat:dataPackItem>
</dat:dataPack>

Access all nodes in xml using linq

I have xml:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<UpdateMemberHireStatus xmlns="http://tempuri.org/">
<member>
<HireAvailability>
<code>1</code>
<name>פנוי</name>
</HireAvailability>
<HireRejectReason>
<code>2</code>
<name>wow</name>
</HireRejectReason>
<IdNumber>43504349</IdNumber>
<note> </note>
</member>
</UpdateMemberHireStatus>
and I want to use LINQ to access all the nodes in the xml.
Here's what I have tried:
XNamespace ns = "tempuri.org/";
IEnumerable<HireStatus> status = from r in doc.Descendants(ns + "UpdateMemberHireStatus")
.Descendants(ns + "member")
select new HireStatus() { };
return status.ToList();
Use Descendants
var xml = XDocument.Load(XMLStream);
var allEle = xml.Descendants("UpdateMemberHireStatus"); //you can do linq now.
You can use XDocument also in the following way:
string xmlPath = "D://member.xml";
XmlDocument doc = new XmlDocument();
xdoc = XDocument.Load(xmlPath);
doc.LoadXml(xdoc.ToString());
var memberStatus= (from mem in xdoc.Descendants("member")
select mem);
foreach (XElement element in memberStatuses.ToList())
IEnumerable<XNode> nodes = element.Nodes();
var x = XElement.Load(XMLStream);
var all = x.DescendantNodes();

Categories

Resources