Get XML attribute Values by its Descendants - c#

I have an XML in this Format and I want to get List of Line ID and its Name
<ArrayOfLines xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<LineStatus ID="0" StatusDetails="">
<BranchDisruptions />
<Line ID="1" Name="Line1" />
<Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
<StatusType ID="1" Description="Line" />
</Status>
</LineStatus>
<LineStatus ID="1" StatusDetails="">
<BranchDisruptions />
<Line ID="2" Name="Line2" />
<Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
<StatusType ID="1" Description="Line" />
</Status>
</LineStatus>
</ArrayOfLines>
and This is the code I have written:
String xmlFilePath = #"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = from c in xmlFile.Descendants("LineStatus") select c;
but it is not returning me any results.

Here is my idea but you have to create list "namesList" and "idList" before. Try this:
XDocument xDoc = XDocument.Load("your xml file");
foreach (var elem in xDoc.Document.Descendants("line"))
{
idList.Add(elem.Attribute("ID").Value);
namesList.Add(elem.Attribute("Name").Value);
}
And you have full controll by index of each list to this data. After that you can also create object of these 2 elements

You have an xml namespace, you need to specify it with element names:
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
var query = from c in xmlFile.Descendants(ns + "LineStatus") select c;

Try this...
String xmlFilePath = #"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = (from c in xmlFile.Descendants("Line")
select new {
ID=c.Attribute("ID").Value,
Name=c.Attribute("Name").Value
}).ToList();;

Related

Extract a node from xml response

Below is my response generated from a webservice.
I want to do such that I want only PresentationElements node from this response.
Any help how can I achieve this query?
<?xml version="1.0"?>
<GetContentResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ExtensionData />
<GetContentResult>
<ExtensionData />
<Code>0</Code>
<Value>Success</Value>
</GetContentResult>
<PresentationElements>
<PresentationElement>
<ExtensionData />
<ContentReference>Product View Pack</ContentReference>
<ID>SHOPPING_ELEMENT:10400044</ID>
<Name>View Pack PE</Name>
<PresentationContents>
<PresentationContent>
<ExtensionData />
<Content>View Pack</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Name</Name>
</PresentationContent>
<PresentationContent>
<ExtensionData />
<Content>Have more control of your home's security and lighting with View Pack from XFINITY Home.</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Description</Name>
</PresentationContent>
<PresentationContent>
<ExtensionData />
<Content>/images/shopping/devices/xh/view-pack-2.jpg</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Image</Name>
</PresentationContent>
<PresentationContent>
<ExtensionData />
<Content>The View Pack includes:
2 Lighting / Appliance Controllers
2 Indoor / Outdoor Cameras</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Feature1</Name>
</PresentationContent>
</PresentationContents>
</PresentationElement>
</PresentationElements>
</GetContentResponse>
You can use XPath extensions
var xdoc = XDocument.Parse(response);
XElement presentations = xdoc.XPathSelectElement("//PresentationElements");
You may use the System.Xml.Linq.XDocument:
//Initialize the XDocument
XDocument doc = XDocument.Parse(yourString);
//your query
var desiredNodes = doc.Descendants("PresentationElements");
Pretty easy, have you tried:
XDocument xml = XDocument.Load("... xml");
var nodes = (from n in xml.Descendants("PresentationElements")
select n).ToList();
You could also project each individual node to an anonymous type using something like:
select new
{
ContentReference = (string)n.Element("ContentReference").Value,
.... etc
}

How to Get Element Names from XElement Using C#?

I have a Xml and i have to get the element name
<Data>
<Test key="G" modifier="control" />
<Test1 key="E" modifier="control" />
<Test3 />
<Test4 />
</Data>
XDocument xd = XDocument.Load("..\\Cmd.xml");
IEnumerable<XElement> xeCmdData = Cmd.XPathSelectElements(".//Data");
foreach (XElement xeData in xeCmdData)
{
// here i am getting the whole xml how to get Element name ...
// Like <Data>
// <Test key="G" modifier="control" />
// <Test1 key="E" modifier="control" />
// <Test3 />
// <Test4 />
// </Data>
}
How to get Element names ?
XDocument xd = XDocument.Load("..\\Cmd.xml");
IEnumerable<string> names = xd.XPathSelectElements("//Data/*")
.Select(e => e.Name.LocalName);
Or without XPath
IEnumerable<string> names = xd.Descendants("Data")
.Elements()
.Select(e => e.Name.LocalName);
Result:
Test
Test1
Test3
Test4

Insert the data of richtextbox into existing xml in c# linq

I have a xml like this:
<?xml version="1.0" encoding="utf-8"?>
<assessment xmlns="http://xml.thinkcentral.com/pub/xml/hsp/assessment" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:tia="http://xml.thinkcentral.com/pub/xml/hsp/tia" xmlns:tibase="http://xml.thinkcentral.com/pub/xml/hsp/tibase" xsi:schemaLocation="http://xml.thinkcentral.com/pub/xml/hsp/assessment http://xml.thinkcentral.com/pub/xml1_2_6/hsp_assessment.xsd" isbn="9780547660455" buid="NA12_AG_G01CH01A" title="Chapter 1 Test Form A" num_questions="24" num_sections="1" type="Basal" intervenable="true" duration="P5Y" pausable="false" scramble="false">
<test_section id="1" name="Chapter 1 Test Form A" index="1">
<aaa testitem_id="NA12_AG_G01CH01A_01" template="hsp_testitem_mc1.xslt" id="1" bankable="true">
<tia:multipleChoiceTestItem total-points="1" questionType="Multiple Choice" sample="false" version_label="1.0">
<tia:directions>
<tia:tiDirectionLine>
<tia:textBody></tia:textBody>
</tia:tiDirectionLine>
<tia:address>Richtextbox Data</tia:address>
</tia:directions>
</tia:multipleChoiceTestItem>
</aaa>
<aaa testitem_id="NA12_AG_G01CH01A_02" template="hsp_testitem_mc1.xslt" id="2" bankable="true">
<tia:multipleChoiceTestItem total-points="1" questionType="Multiple Choice" sample="false" version_label="1.0">
<tia:directions>
<tia:tiDirectionLine>
<tia:textBody></tia:textBody>
</tia:tiDirectionLine>
<tia:address>Richtextbox Data</tia:address>
</tia:directions>
</tia:multipleChoiceTestItem>
</aaa>
</test_section>
</assessment>
I have to insert the the data according to the id of the aaa element.
<aaa testitem_id="NA12_AG_G01CH01A_01" template="hsp_testitem_mc1.xslt" id="1" bankable="true">
<aaa testitem_id="NA12_AG_G01CH01A_02" template="hsp_testitem_mc1.xslt" id="2"bankable="true">
if id="1" then data of ritchtextbox will be insert into tia:address node.
i am using the following code.
private void button2_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load(#"d:\file.xml");
XNamespace ns = XNamespace.Get("http://tia.com");
var result= (from ele in doc.Descendants("aaa")
where ((string)ele.Attribute("id")) == "1"
select ele.Element(ns+"address")).FirstOrDefault();
if (result != null)
{
result.Value = richTextBox1.Text;
doc.Save(#"d:\file.xml");
}
MessageBox.Show("done");
}
its not working. how i do that?
First of al, the XML markup you have posted is not valid. I think the easiest way to read/write an XML document is Linq-XML. You have to import System.Xml.Linq namespace to use XDocument class and its method. Take a look at MSDN article.
XDocument doc = XDocument.Load(#"c:\file.xml");
var result = (from ele in doc.Descendants("aaa")
where ((string)ele.Attribute("id")) == "1"
select ele.Element("address")).FirstOrDefault();
if (result != null)
{
result.Value = richTextBox1.Text;
doc.Save(#"c:\file.xml");
}
XML document should be:
<?xml version="1.0" encoding="utf-8"?>
<root>
<aaa id="1">
<address>Hello World</address>
</aaa>
<aaa id="2">
<address>
write text of ritchtextbox here</address>
</aaa>
</root>
EDIT:
In OP, XML markup has some issues and I've fixes the markup (added namespace).
<?xml version="1.0" encoding="utf-8"?>
<aaa testitem_id="chapter1" template="hsp_testitem_mc1.xslt" id="1" bankable="true" xmlns:tia="http://tia.com">
<tia:multipleChoiceTestItem total-points="1" questionType="Multiple Choice" sample="false" version_label="1.0">
<tia:directions>
<tia:tiDirectionLine>
<tia:textBody />
</tia:tiDirectionLine>
<tia:address>I have to edited here.(Richtextbox data)</tia:address>
</tia:directions>
</tia:multipleChoiceTestItem>
</aaa>
Code to find <tia:address> and replace its value.
XDocument doc = XDocument.Load(file);
XNamespace ns = XNamespace.Get("http://tia.com");
var result = (from ele in doc.Descendants(ns + "address")
select ele).SingleOrDefault();
if (result != null)
{
result.Value = richTextBox1.Text;
doc.Save(file);
}
EDIT : After changes made by OP in opening post.
XDocument doc = XDocument.Load(file);
//Change the namespace
XNamespace ns = XNamespace.Get("http://xml.thinkcentral.com/pub/xml/hsp/tia");
var result = (
from ele in doc.Descendants(ns + "multipleChoiceTestItem")
where ele.Parent.Attribute("id").Value == "1"
select
ele.Descendants(ns+"address").FirstOrDefault()
).FirstOrDefault();
if (result != null)
{
result.Value = "World";
doc.Save(file);
}

Linq to XML Read xml file using linq

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Report SYSTEM "https://abc.mycompany.com/abc/processingreports/processeddtd/abcd_1_8.dtd">
<Report Name="Daily TRANSACTIONS"
Version="1.8"
xmlns="https://abc.mycompany.com/abc/processingreports/processeddtd/abcd_1_8.dtd"
OrgID="ABC_PQR" StartDate="2011-03-10T00:00:00+00:00" EndDate="2011-03-11T00:00:00+00:00">
<Requests>
<Request ID="2"
Date="2011-03-10T00:21:14+00:00"
OrderNumber="1">
<BillTo>
<FirstName />
</BillTo>
<LineItems>
<LineItem Number="0">
<Quantity />
</LineItem>
</LineItems>
</Request>
<Request ID="2"
Date="2011-03-10T00:21:14+00:00"
OrderNumber="1">
TransactionNumber="389958330911111">
<BillTo>
<FirstName>A</FirstName>
</BillTo>
<LineItems>
<LineItem Number="0">
<Quantity>1</Quantity>
</LineItem>
</LineItems>
<UniqueData>
<UniqueNumber>11111111111111111111111111111</UniqueNumber>
</UniqueData></Request></Requests></Report>
In above XML file using Linq i just
want to extract OrderNumber and
UniqueNumber
OrderNumber="1"
11111111111111111111111111111
Any ideas, suggestions to extract these details?
I can select elements from above xml file but UniqueNumber is not associated with OrderNumber
I am looking for something below (ignore lines where UniqueNumber is not present)
OrderNumber - assosicated UniqueNumber
Update
In "requiredElements" i am expecting two coulmns OrderNumber and UniqueNumber and holding associated values with each other as 1 and 11111 and so one
#region FileOpen with UTF8 Encoding
TextReader sr = new StreamReader(cFileName, Encoding.UTF8);
XDocument reportfile = XDocument.Load(sr, LoadOptions.SetBaseUri);
XElement xd = XElement.Parse(reportfile.ToString());
sr.Close();
#endregion
XNamespace ns = xd.Attribute("xmlns").Value;
var requiredElements = (from resultquery in reportfile.Descendants()
select new
{
OrderNumber = resultquery.Attribute("OrderNumber"),
UniqueNumber= (string)resultquery.Element(AddNameSpace(ns, "UniqueNumber")),
}
);
Here is some sample:
XDocument doc = XDocument.Load(#"file.xml");
XNamespace df = doc.Root.Name.Namespace;
var results = from request in doc.Descendants(df + "Request")
where request.Elements(df + "UniqueData").Elements(df + "UniqueNumber").Any()
select new
{
ordNumber = (int)request.Attribute("OrderNumber"),
uniqueNumber = (decimal)request.Element(df + "UniqueData").Element(df + "UniqueNumber")
};
foreach (var result in results)
{
Console.WriteLine("{0}-{1}", result.ordNumber, result.uniqueNumber);
}

How to read XML Nodes in XML using c#.net

I have a XML file like below:
<report timestamp="3201" reportVersion="2" request="3981135340">
<question timedOut="false" time="3163" attempts="2" correct="true" id="13">
<answer status="attempt">
<radioButton correct="false" value="true" id="17" />
</answer>
<answer status="correct">
<radioButton correct="true" value="true" id="15" />
</answer>
</question>
</report>
I want to read the child nodes based on 'status' attribute of 'answer' node.
Use XmlReader (fastest but forward only), XDocument (LINQ to XML) or XmlDocument. See the examples in the msdn documentation.
Using LINQ to XML:
using System.Xml.Linq;
var doc = XDocument.Parse(xml); // or XDocument.Load()
var elements = from e in doc.Descendants("answer")
where e.Attribute("status").Value == "attempt"
select e;
// elements will be IEnumerable<XElement>
Use XmlDocument and XPath:
XmlDocument document = new XmlDocument();
//here you should load your xml for example with document.Load();
XmlNodeList nodes = document.SelectNodes("/report/question/answer[#status = 'correct']/radioButton");
Just modify the XPath to your needs.
try this one..
foreach (XmlNode xnode in xdoc.SelectNodes("report/question/answer"))
{
if (xnode.Attributes.GetNamedItem("status").Value == "correct")
{
string value = xdoc.SelectSingleNode("report/question/answer[#status='correct']/radioButton").Attributes.GetNamedItem("id").Value;
}
if (xnode.Attributes.GetNamedItem("status").Value == "attempt")
{
string value = xdoc.SelectSingleNode("report/question/answer[#status='attempt']/radioButton").Attributes.GetNamedItem("id").Value;
}
}

Categories

Resources