Below is my XML file
<MultiCentreDeals>
<DealItem>
<ID>24</ID>
<Days>
<Day>
<DayID>24-1</DayID>
<DayTitle>Day 13</DayTitle>
<Title>Meeting Point</Title>
<HotelName>15</HotelName>
</Day>
<Day>
<DayID>24-2</DayID>
<DayTitle>Day 2</DayTitle>
<Title>Departure to Test</Title>
<HotelName>54</HotelName>
</Day>
</Days>
</DealItem>
</MultiCentreDeals>
I want to delete the XML node set belong to ID 24 and DayID 24-2. Can anyone explain how to do this.
XDocument is your friend.
// Parse your XML string
var doc = XDocument.Parse(xml);
// Find the first child of type "Day", whose child of type "DayID" has the value "24-2"
var toRemove = doc.Root
.Descendants("Day")
.FirstOrDefault(x => x.Element("DayID").Value == "24-2");
// Remove it
toRemove?.Remove();
string result = doc.ToString();
Related
I have an xml which is string. This is part of it.
<GetModuleInfoResult xmlns =\"http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Results\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
<Code>0</Code>
<Message i:nil=\"true\"/>
<Parameters xmlns:a=\"http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities\">
<a:Parameter>
<a:Key>width</a:Key>
<a:Value>1068</a:Value>
</a:Parameter>
<a:Parameter>
<a:Key>height</a:Key>
<a:Value>600</a:Value>
</a:Parameter>
I want to get all the parameter nodes and read their 'key' and 'Value' nodes.
How can I achieve that?
Here is one way to grab the key-value pairs from your xml
XDocument doc = XDocument.Load(/* YOUR XML FILE **/);
XNamespace x = "http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities";
var parameters = doc.Descendants(x + "Parameter").ToDictionary(e => e.Descendants(x + "Key").First().Value, e => e.Descendants(x + "Value").First().Value);
<?xml version="1.0"?>
<TextType IsKey="false" Name="XMLReport"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Providers
xmlns="Reporting"/>
<Sales
xmlns="Reporting"/>
<Value
xmlns="Reporting">
<?xml version="1.0" encoding="utf-8"?>
<TestReport>
<StudyUid>
<![CDATA[123]]>
</StudyUid>
<Modality>
<![CDATA[XYZ]]>
</Modality>
<StudyDate format="DICOM">123456</StudyDate>
<StudyTime format="DICOM">6789</StudyTime>
<AccessionNumber>
<![CDATA[123]]>
</AccessionNumber>
<StudyDescription>
<![CDATA[abc def]]>
</StudyDescription>
<OperatorName format="xyz">
<![CDATA[abc]]>
</OperatorName>
<PhysicianReadingStudy format="xyz">
<![CDATA[^^^^]]>
</PhysicianReadingStudy>
<InstitutionName>
<![CDATA[xyz]]>
</InstitutionName>
<HospitalName>
<![CDATA[Hospital Name]]>
</HospitalName>
<ReportSet>
<MyReport ID="1">
<ReportStatus>
<![CDATA[Done]]>
</ReportStatus>
</MyReport>
<MyReport ID="2">
<ReportStatus>
<![CDATA[Done]]>
</ReportStatus>
</MyReport>
<MyReport ID="3">
<ReportStatus>
<![CDATA[Initial]]>
</ReportStatus>
</MyReport>
</ReportSet>
<ReportImageSet />
<FetusSet />
</TestReport>
</Value>
<WhoSetMe xmlns="Reporting">NotSpecified
</WhoSetMe>
</TextType>
I want to parse the xml above in C# and check whether "ReportStatus" is "Done" for all the ReportStatus under MyReport/ReportSet. One more twist here is the xml contains one more xml starts at "Value" tag as in above example.It may contatin many ReportStatus tag under ReportSet tag. Can someone please help me?
// Can you try this? I tried to do it with LINQ to XML.
// I assume you have multiple <TestReport /> elements in <Value /> tag
// and var xelement is your xml variable
// First we get all TestReport elemnts
IEnumerable<XElement> allReports =
from el in xelement.Elements("TextType/Value/TestReport")
select el;
// From allReports we get all MyReport elemnts
IEnumerable<XElement> allMyReports =
from el in allReports.Elements("ReportSet/MyReport")
select el;
// From allReports we also get all MyReport elemnts with element ReportStatus value equals "Done"
IEnumerable<XElement> allDoneMyReports =
from el in allMyReports
where (string)el.Element("ReportStatus") == "Done"
select el;
// Now we compare allMyReport with allDoneMyReports
if (allMyReports.Count() == allDoneMyReports.Count())
{
//DO Somehing
}
Your XML document is invalid. You need to fix it before trying to parse it. The issue is that a document can only have one top-level element; you have 2 <TextType> and <Providers>.
Most of your elements are the namespace Reporting. You need to use it when referencing the element.
XNamespace ns = "Reporting";
var value = doc.Element("Value" + ns);
Update
Just use the namespace for each element
XNamespace ns = "Reporting";
var value = xelement.Elements("Value" + ns);
Another Update
The XML document is considered invalid because it has multiple XML declarations; there is no way to disable this. I suggest you pre-process the document to remove the extra declarations. Here's an example (https://dotnetfiddle.net/UnuAF6)
var xml = "<?xml version='1.0'?><a> <?xml version='1.0'?><b id='b' /></a>";
var doc = XDocument.Parse(xml.Replace(" <?xml version='1.0'?", " "));
var bs = doc.Descendants("b");
Console.WriteLine("{0} 'b' elements", bs.Count());
For example, I have this xml string:
<?xml version="1.0" encoding="utf-8"?>
<data>
<text>How to get <bold>all</bold> this string's content?</text>
</data>
I want to get all these elements in an array of objects (for each object I have a class), without loosing their structure:
[1] (TextClass; where bold = false) How to get
[2] (TextClass; where bold = true) all
[3] (TextClass; where bold = false) this string's content?
All I'm getting using XmlDocument and XmlNode classes right now is InnerText Or InnerXml separately.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("example.xml");
foreach (XmlNode child in xmlDoc.DocumentElement.ChildNodes)
{
string chName = child.Name; // text
string text = child.InnerText; // How to get all this string's content?
string xml = child.InnerXml; // How to get <bold>all</bold>this string's content?
}
Is it possible?
For this kind of work I think it is easier to use the LINQ to XML.
In your example something like the following could work (depending on exactly what you want to achieve):
XDocument doc = XDocument.Parse(xml);
var textClasses = from n in doc.Descendants("text").DescendantNodes()
where n.NodeType == XmlNodeType.Text
select new { text = ((XText)n).Value, bold = n.Parent?.Name == "bold" };
And a .net fiddle so you can quickly see the result.
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Message>
<MessageID>1</MessageID>
<Product>
<SKU>33333-01</SKU>
</Product>
</Message>
</Envelope>
I've tried googling but whether I'm just not providing the correct search criteria I don't know.
I want to be able to search the XML file based on the MessageID and then grab the SKU.
I then want to search another XML file based on the SKU and remove that message completely.
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Message>
<MessageID>1</MessageID>
<Inventory>
<SKU>33333-01</SKU>
<Quantity>1</Quantity>
</Inventory>
</Message>
<Message>
<MessageID>2</MessageID>
<Inventory>
<SKU>22222-01</SKU>
<Quantity>1</Quantity>
</Inventory>
</Message>
</Envelope>
Meaning the XML above becomes:
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Message>
<MessageID>2</MessageID>
<Inventory>
<SKU>22222-01</SKU>
<Quantity>1</Quantity>
</Inventory>
</Message>
</Envelope>
To confirm I cannot confirm that the MessageID will be the same over different XML files.
Thanks in advance for any help.
My questions:
How do I search through XML files?
How do I then grab another Nodes details
Can I remove a complete from an XML file based on a search?
You can use XmlDocument to load your XML document. Then, you can use XPath for searching any nodes.
XmlDocument document = new XmlDocument();
document.Load("C:\fileOnTheDisk.xml");
// or
document.LoadXml("<a>someXmlString</a>");
// Returns single element or null if not found
var singleNode = document.SelectSingleNode("Envelope/Message[MessageID = '1']");
// Returns a NodeList
var nodesList = document.SelectNodes("Envelope/Message[MessageID = '1']");
Read more about XPath at w3schools.com.
Here is a good XPath Tester.
For example, you can use the following XPath to find nodes in your document by ID:
XmlDocument document = new XmlDocument();
document.Load("C:\doc.xml");
var node = document.SelectSingleNode("Envelope/Message[MessageID = '1']");
var sku = node.SelectSingleNode("Inventory/SKU").InnerText;
Console.WriteLine("{0} node has SKU = {1}", 1, sku);
Or you can output all SKUs:
foreach (XmlNode node in document.SelectNodes("Envelope/Message"))
{
Console.WriteLine("{0} node has SKU = {1}",
node.SelectSingleNode("MessageID").InnerText,
node.SelectSingleNode("Inventory/SKU").InnerText);
}
It will produce:
1 node has SKU = 33333-01
2 node has SKU = 22222-01
Note that there are possible NullReferenceExceptions if nodes are not present.
You can simply remove it using RemoveChild() method of its parent.
XmlDocument document = new XmlDocument();
document.Load("C:\doc.xml");
var node = document.SelectSingleNode("Envelope/Message[MessageID = '1']");
node.ParentNode.RemoveChild(node);
document.Save("C:\docNew.xml"); // will be without Message 1
You can use Linq to XML to do this:
var doc= XDocument.Load("input.xml");//path of your xml file in which you want to search based on message id.
var searchNode= doc.Descendants("MessageID").FirstOrDefault(d => d.Value == "1");// It will search message node where its value is 1 and get first of it
if(searchNode!=null)
{
var SKU=searchNode.Parent.Descendants("SKU").FirstOrDefault();
if(SKU!=null)
{
var searchDoc=XDocument.Load("search.xml");//path of xml file where you want to search based on SKU value.
var nodes =searchDoc.Descendants("SKU").Where(d=>d.Value==SKU.Value).Select(d=>d.Parent.Parent).ToList();
nodes.ForEach(node=>node.Remove());
searchDoc.Save("output.xml");//path of output file
}
}
I'd recommend you did this using LINQ to XML - it's much nicer to work with than the old XmlDocument API.
For all the examples, you can parse your XML string xml to an XDocument like so:
var doc = XDocument.Parse(xml);
1. How do I search through XML files?
You can get the SKU for a specific message ID by querying your document:
var sku = (string)doc.Descendants("Message")
.Where(e => (int)e.Element("MessageID") == 1)
.SelectMany(e => e.Descendants("SKU"))
.Single();
2. How do I then grab another Nodes details?
You can get the Message element with a specified SKU using a another query:
var message = doc.Descendants("SKU")
.Where(sku => (string)sku == "33333-01")
.SelectMany(e => e.Ancestors("Message"))
.Single();
3. Can I remove a complete element from an XML file based on a search?
Using your result from step 2, you can simple call Remove:
message.Remove();
Alternatively, you can combine the query from step 2 and simply execute a command to remove any messages that have a specific SKU:
doc.Descendants("SKU")
.Where(sku => (string)sku == "33333-01")
.SelectMany(e => e.Ancestors("Message"))
.Remove();
I tried to answer all your questions:
using System.Xml.XPath;
using System.Xml.Linq;
XDocument xdoc1 = XDocument.Load("xml1.xml");
XDocument xdoc2 = XDocument.Load("xml2.xml");
string sku = String.Empty;
string searchedID = "2";
//1.searching through an xml file based on path
foreach (XElement message in xdoc1.XPathSelectElements("Envelope/Message"))
{
if (message.Element("MessageID").Value.Equals(searchedID))
{
//2.grabbing another node's details
sku = message.XPathSelectElement("Inventory/SKU").Value;
}
}
foreach (XElement message in xdoc2.XPathSelectElements("Envelope/Message"))
{
if (message.XPathSelectElement("Inventory/SKU") != null && message.XPathSelectElement("Inventory/SKU").Value.Equals(sku))
{
//removing a node
message.Remove();
}
}
xdoc2.Save("xml2_del.xml");
}
How can I get the value of a Node in a XDocument when don't has more childs ?
<Contacts>
<Company>
<Name>Testing</Name>
<ID>123</ID>
</Company>
</Contacts>
In this case, I wanna get the value of the <Name> and <ID> element, because don't has child elements in them.
I'm trying the follow
protected void LeXMLNode(HttpPostedFile file)
{
XmlReader rdr = XmlReader.Create(file.FileName);
XDocument doc2 = XDocument.Load(rdr);
foreach (var name in doc2.Root.DescendantNodes().OfType<XElement>().Select(x => x.Name).Distinct())
{
XElement Contact = (from xml2 in doc2.Descendants(name.ToString())
where xml2.Descendants(name.ToString()).Count() == 0
select xml2).FirstOrDefault();
string nome = name.ToString();
}
}
but without success, because my foreach pass in all Elements and I wanna get just the value of Elements that don't has childs.
document.Root.Elements("Company").Elements()
.Where(item => !item.HasElements).ToList();
See XElement.HasElements: http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.haselements.aspx