How to hold more than one values in XML element? - c#

xWaarde.Value is overriding with new values and flushing old values.
how to stored multiple values in Xelement.
private XElement[] AddCoordinatenList(XElement childElements)
{
XmlNode xmlCoordinatenNode = Utility.GetMappingValues(Constants.BMCoordinaten, ConnectionType.BM);
XmlNode xWaardeNode = Utility.GetMappingValues(Constants.BMXwaarde, ConnectionType.BM);
XmlNode yWaardeNode = Utility.GetMappingValues(Constants.BMYwaarde, ConnectionType.BM);
XmlNode CoordinateX = Utility.GetMappingValues(Constants.XCoordinate, ConnectionType.BM);
XmlNode CoordinateY = Utility.GetMappingValues(Constants.YCoordinate, ConnectionType.BM);
var coordinatenList = from document in childElements.DescendantsAndSelf() where document.Name.LocalName == xmlCoordinatenNode.Name select document;
List<XElement> xcoordinatenList = new List<XElement>();
XElement xWaarde = new XElement(CoordinateX.Name);
XElement yWaarde = new XElement(CoordinateY.Name);
if (coordinatenList.Count() > 0)
{
foreach (XElement element in coordinatenList.Descendants())
{
if (element.Name.LocalName == xWaardeNode.Name)
{
xWaarde.Value = element.Value;
}
if (element.Name.LocalName == yWaardeNode.Name)
{
yWaarde.Value = element.Value;
}
}
}
return xcoordinatenList.ToArray();
}

It's not possible. Use Attributes:
XAttribute attribute = new XAttribute("name1", <value>);
element.Add(attribute);
attribute = new XAttribute("name2", <value>);
element.Add(attribute);
You can also add a list of child elements or add all strings as one string, separated by a comma for instance.

Related

Need help retrieving XML data using Linq

I am trying to retrieve data from an XML file and return the parsed data in a list. Depending on what I use to access the data (Element or Attributes) I either get null (in case of Element) or something I cannot decipher (in case of Attributes).
XML Looks like this:
<DATA_RESPONSE>
<HEADER>
<MSGID>IS20101P:091317125610:98::34:0</MSGID>
</HEADER>
<DATA>
<ROW ID='IS20101P' PE_NAME='APP-029' PE_ID='4' CODE='4829' DATA='5,1,500,1' />
<ROW ID='IS20101P' PE_NAME='APPS-029' PE_ID='4' CODE='4829' DATA='4,1,500,1' />
...
</DATA>
<SUMMARY>
</SUMMARY>
<ERRORS>
</ERRORS>
</DATA_RESPONSE>
I am using the following to get the data. I read the file and store XML in a string and call a method with this string as argument:
public static Hashtable GetIDSData(string sXMLString)
{
Hashtable result = new Hashtable();
result.Add("Success", false);
result.Add("ErrorMessage", "");
result.Add("ID", "");
result.Add("PE_NAME", "");
result.Add("PE_ID", "");
result.Add("CODE", "");
result.Add("DATA", "");
xmlDoc.InnerXml = sXMLString;
XmlElement root = xmlDoc.DocumentElement;
XDocument doc = XDocument.Parse(sXMLString);
XmlNode node = xmlDoc.SelectSingleNode("DATA_RESPONSE/DATA");
if (node != null)
{
var AddressInfoList = doc.Root.Descendants("ROW").Select(Address => new
{
ID = Address.Attributes("ID")?.ToString(),
PEName = Address.Attributes("PE_NAME")?.ToString(),
PEID = Address.Attributes("PE_ID")?.ToString(),
Code = Address.Attributes("CODE")?.ToString(),
Data = Address.Attributes("DATA")?.ToString(),
}).ToList();
foreach (var AddressInfo in AddressInfoList)
{
if (string.IsNullOrEmpty(AddressInfo.Code))
{
result["Success"] = false;
result["ErrorMessage"] = "Invalid Code; code is empty.";
}
else
{
result["Success"] = true;
result["ErrorMessage"] = "";
result["ID"] = AddressInfo.ID;
result["PE_NAME"] = AddressInfo.PEName;
result["PE_ID"] = AddressInfo.PEID;
result["CODE"] = AddressInfo.Code;
result["DATA"] = AddressInfo.Data;
}
}
return result;
}
In Linq section, if I use Address.Element("ID").Value, I get null returned.
There is no namespace used in XML.
First off, the GetIDSData() method does not compile as is, because at the line xmlDoc.InnerXml = sXMLString, xmlDoc has not been defined.
I'm assuming you want xmlDoc to be an XmlDocument loaded with the contents of the sXMLString parameter, so I'm changing that line to:
XmlDocument xmlDoc = new XmlDocument {InnerXml = sXMLString};
Also, your root variable is never used, so I removed it for clarity.
Now as for the main part of your question, given your current syntax, you are calling .ToString() on a collection of attributes, which is obviously not what you want. To fix this, when you're iterating the AddressInfoList, You want to fetch the attribute values like:
ID = Address.Attributes("ID")?.Single().Value
or
ID = address.Attribute("ID")?.Value
...rather than Address.Attributes("ID")?.ToString() as you have above.
You are not selecting values of attributes. In your code you are selecting attributes. Not sure what are you trying to achieve, but here is my modified version of your code that loads all elements into DataTable
public static DataTable GetIDSData(string sXMLString)
{
DataTable result = new DataTable();
result.Columns.Add("Success");
result.Columns.Add("ErrorMessage");
result.Columns.Add("ID");
result.Columns.Add("PE_NAME");
result.Columns.Add("PE_ID");
result.Columns.Add("CODE");
result.Columns.Add("DATA");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.InnerXml = sXMLString;
XmlElement root = xmlDoc.DocumentElement;
XDocument doc = XDocument.Parse(sXMLString);
XmlNode node = xmlDoc.SelectSingleNode("DATA_RESPONSE/DATA");
if (node != null)
{
var AddressInfoList = doc.Root.Descendants("ROW").Select(Address => new
{
ID = Address.Attributes("ID").Select(i=>i.Value) ,
PEName = Address.Attributes("PE_NAME").Select(i=>i.Value),
PEID = Address.Attributes("PE_ID").Select(i=>i.Value),
Code = Address.Attributes("CODE").Select(i=>i.Value),
Data = Address.Attributes("DATA").Select(i=>i.Value),
}).ToList();
AddressInfoList.ForEach(e =>
{
e.Code.ToList().ForEach(c =>
{
DataRow row = result.NewRow();
if (!string.IsNullOrEmpty(c))
{
row["Success"] = true;
row["ErrorMessage"] = "";
row["ID"] = e.ID.First();
row["PE_NAME"] = e.PEName.First();
row["PE_ID"] = e.PEID.First();
row["CODE"] = e.Code.First();
row["DATA"] = e.Data.First();
}
else
{
row["Success"] = false;
row["ErrorMessage"] = "Invalid Code; code is empty.";
}
result.Rows.Add(row);
});});
result.Dump();
return result;
}
return result;
}
And this is the result that you will get in your datatable.
ID = Address.Attributes("ID")?.ToString(),
You want to use Attribute(name) (without s) instead:
ID = Address.Attributes("ID")?.Value,

How to set a value in XML using C#?

How to change the value of sourcePatientInfo in the following xml file using c#.
I can able to read the value using,
var elem = (from n in xml.Descendants("Slot")
where n.Attribute("name").Value == "sourcePatientInfo"
select n).FirstOrDefault();
How to change the same using C#?
<?xml version="1.0" encoding="utf-8"?>
<rs:SubmitObjectsRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rs="urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1" xmlns:rim="urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1" xmlns="urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1">
<LeafRegistryObjectList>
<ObjectRef id="urn:uuid:93606bcf-9494-43ec-9b4e-a7748d1a838d" />
<ExtrinsicObject id="Document01" mimeType="application/dicom" objectType="urn:uuid:7edca82f-054d-47f2-a032-9b2a5b5186c1">
<Name>
<LocalizedString value="Physical" />
</Name>
<Description />
<Slot name="sourcePatientId">
<ValueList>
<Value>pid1^^^&1.2.3&ISO</Value>
</ValueList>
</Slot>
<Slot name="sourcePatientInfo">
<ValueList>
<Value>PID-3|pid1^^^&1.2.3&ISO</Value>
<Value>PID-5|Doe^John^^^</Value>
<Value>PID-7|19560527</Value>
<Value>PID-8|M</Value>
<Value>PID-11|100 Main St^^Metropolis^Il^44130^USA</Value>
</ValueList>
</Slot>
I would like to change the values using c#. Am not able to figure out the way. Any Help to resolve this issue will be appreciated.
I want to change the
<Slot name="sourcePatientInfo">
<ValueList>
<Value>PID-3|pid1^^^&1.2.3&ISO</Value>
<Value>PID-5|Doe^John^^^</Value>
to the following value
<Slot name="sourcePatientInfo">
<ValueList> <Value>PID-3|MyPID</Value>
<Value>PID-5|MyName</Value>
I have also tried the following the code,
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc1.NameTable);
namespaceManager.AddNamespace("rs", "urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1");
var query = "/rs:SubmitObjectsRequest/LeafRegistryObjectList/ExtrinsicObject";
XmlNodeList nodeList = xmlDoc1.SelectNodes(query, namespaceManager);
foreach (XmlNode node1 in nodeList)
{
if (node1.Attributes["Slot"].Value == "sourcePatientInfo")
{
node1.Attributes["ValueList"].Value = "Myvalue";
}
}
In this code, nodelist.count is always zero :-(. Kindly help me to resolve the issue.
If you need to update first two values:
var slot = xml.Descendants("Slot")
.Where(n => n.Attribute("name").Value == "sourcePatientInfo")
.FirstOrDefault();
if(slot == null)
{
throw new WhateverAppropriateHereEcxeption();
}
var values = slot.Descendants("Value").ToList();
if(values.Count < 2)
{
throw new WhateverAppropriateHereEcxeption();
}
values[0].Value = "PID-3|MyPID" // updating the first value
values[1].Value = "PID-5|MyName" // updating the second value
if you have to search by value you can do:
bool UpdateValue(XElement slot, string oldValue, string newValue)
{
var elem = slot.Descendants("Slot")
.Where(n => n.Name == "Value" && n.Value == oldValue)
.FirstOrDefault();
if(elem != null)
{
elem = newValue;
return true;
}
return false;
}
and inside some function
var slot = xml.Descendants("Slot")
.Where(n => n.Attribute("name").Value == "sourcePatientInfo")
.FirstOrDefault();
if(slot == null)
{
throw new WhateverAppropriateHereEcxeption();
}
UpdateValue(slot, "PID-3|pid1^^^&1.2.3&ISO", "PID-3|MyPID");
UpdateValue(slot, "PID-5|Doe^John^^^", "PID-5|MyName");
UPD when you call xml.Descendants("Slot") xml look only for elements in default namespace. I use an extension method as a quick workaround to avoid that:
public static IEnumerable<XElement> NsDescendants(this XContainer e, string elementName)
{
return e.Descendants().Where(d => d.Name.LocalName == elementName);
}
Finally my problem is solved with the following code.
XmlDocument xmlDocSOR = new XmlDocument();
XmlDocSOR.Load("filename.xml");
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocSOR.NameTable);
namespaceManager.AddNamespace("rs", "urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1");
namespaceManager.AddNamespace("ns", "urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1");
var query = "/rs:SubmitObjectsRequest/ns:LeafRegistryObjectList/ns:ExtrinsicObject/ns:Slot";
XmlNodeList nodeList = xmlDocSOR.SelectNodes(query, namespaceManager);
foreach (XmlNode plainnode in nodeList)
{
if (plainnode.Attributes["name"].Value == "sourcePatientId")
{
XmlNode childnode = plainnode.LastChild;
XmlElement ee1 = (XmlElement)childnode.FirstChild;
ee1.InnerText = sPatientID;
}
}
xmlDocSOR.Save("filename.xml");

Adding Subroot elements in XML

I'm making an XML Document which contains subroot nodes. I'm using XmlDocument and adding the child nodes.
This is my code:
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);
XmlElement root = doc.CreateElement("LICENSE");
if (strGInfo == "")
{
strGInfo = "N/A";
}
XmlElement ginfo = doc.CreateElement("GENERAL_INFO");
ginfo.InnerText = strGInfo;
root.AppendChild(ginfo);
if (strLNo == "")
{
strLNo = "N/A";
}
XmlElement subroot = doc.CreateElement("LICENSE_INFO");
//XmlElement root1 = doc.CreateElement("LICENSE_INFO");
XmlElement lno = doc.CreateElement("LICENCE_NO");
lno.InnerText = txtLNo.Text;
subroot.AppendChild(lno);
if (strUID == "")
{
strUID = "N/A";
}
XmlElement uid = doc.CreateElement("USER_ID");
uid.InnerText = txtUID.Text;
subroot.AppendChild(uid);
if (strOrg == "")
{
strOrg = "N/A";
}
XmlElement org = doc.CreateElement("ORGANIZATION");
org.InnerText = txtOrg.Text;
subroot.AppendChild(org);
if (strUName == "")
{
strUName = "N/A";
}
XmlElement uname = doc.CreateElement("USER_NAME");
uname.InnerText = txtUName.Text;
subroot.AppendChild(uname);
if (strSType == "")
{
strSType = "N/A";
}
XmlElement stype = doc.CreateElement("SOLUTION_TYPE");
stype.InnerText = txtSType.Text;
subroot.AppendChild(stype);
if (strVer == "")
{
strVer = "N/A";
}
XmlElement ver = doc.CreateElement("VERSION");
ver.InnerText = txtVer.Text;
subroot.AppendChild(ver);
XmlElement ltype = doc.CreateElement("LICENCE_TYPE");
ltype.InnerText = drpLType.SelectedItem.Text;
subroot.AppendChild(ltype);
if (strMeapSupp == "")
{
strMeapSupp = "N/A";
}
XmlElement meapsupp = doc.CreateElement("MEAP_SUPPORT");
meapsupp.InnerText = rdoMeapSupport.Text;
subroot.AppendChild(meapsupp);
XmlElement LicFrom = doc.CreateElement("LICENCE_FROM");
LicFrom.InnerText = lblLFrom.Text;
subroot.AppendChild(LicFrom);
XmlElement LicTo = doc.CreateElement("LICENCE_TO");
LicTo.InnerText = lblLTo.Text;
subroot.AppendChild(LicTo);
XmlElement suppfrom = doc.CreateElement("SUPPORT_FROM");
suppfrom.InnerText = lblSuppFrom.Text;
subroot.AppendChild(suppfrom);
XmlElement suppto = doc.CreateElement("SUPPORT_TO");
suppto.InnerText = lblSuppTo.Text;
subroot.AppendChild(suppto);
doc.AppendChild(subroot);
XmlElement subroot2 = doc.CreateElement("LICENCE_CONSTRAINT");
if (strMaxUsr == "")
{
strMaxUsr = "N/A";
}
XmlElement maxusr = doc.CreateElement("MAX_USER");
maxusr.InnerText = txtMaxUsr.Text;
subroot2.AppendChild(maxusr);
if (strMaxMach == "")
{
strMaxMach = "N/A";
}
XmlElement maxmach = doc.CreateElement("MAX_MACHINE");
maxmach.InnerText = txtMaxMach.Text;
subroot2.AppendChild(maxmach);
if (strMachIP == "")
{
strMachIP = "N/A";
}
doc.AppendChild(subroot2);
XmlElement subroot3 = doc.CreateElement("MACHINE_INFO");
XmlElement machip = doc.CreateElement("MACHINE_IP");
machip.InnerText = txtMachIP.Text;
subroot3.AppendChild(machip);
if (strMachMac == "")
{
strMachMac = "N/A";
}
XmlElement machmac = doc.CreateElement("MACHINE_MAC");
machmac.InnerText = txtMachMac.Text;
subroot3.AppendChild(machmac);
doc.AppendChild(subroot3);
XmlElement subroot4 = doc.CreateElement("LICENCE_SIGNATURE");
XmlElement UqID = doc.CreateElement("UNIQUE_ID");
UqID.InnerText = txtUqID.Text;
subroot4.AppendChild(UqID);
doc.AppendChild(subroot4);
doc.Save(#"D:\New.xml");
My XML Document should look something like this:
-<LICENSE>
<GENERAL_INFO> </GENERAL INFO>
-<LICENSE_INFO>
<LICENSE_NO> </LICENSE_NO>
<USER_ID> </USER_ID> //etc
-<LICENCE_CONSTRAINT>
<MAX_USER> </MAX_USER>
<MAX_MACHINE> </MAX_MACHINE>
</LICENCE_CONSTRAINT>
-<MACHINE_INFO>
<MACHINE_IP> </MACHINE_IP>
<MACHINE_MAC> </MACHINE_MAC>
</MACHINE_INFO>
</LICENSE_INFO>
Where am I going wrong?
I would use Linq2Xml for this
string xml = FormXml(licenceNo: "1",machineIP:"1.2.3.4",generalInfo:"some Info");
public string FormXml(
string generalInfo="N/A",
string licenceNo="N/A",
string userID="N/A",
string maxUser="N/A",
string maxMachine="N/A",
string machineIP="N/A",
string machineMAC="N/A")
{
return new XElement("LICENSE",
new XElement("GENERAL_INFO", generalInfo),
new XElement("LICENSE_INFO",
new XElement("LICENSE_NO", licenceNo),
new XElement("USER_ID", userID)),
new XElement("LICENCE_CONSTRAINT",
new XElement("MAX_USER", maxUser),
new XElement("MAX_MACHINE", maxMachine)),
new XElement("MACHINE_INFO",
new XElement("MACHINE_IP", machineIP),
new XElement("MACHINE_MAC", machineMAC))).ToString();
}
and OUTPUT:
<LICENSE>
<GENERAL_INFO>some Info</GENERAL_INFO>
<LICENSE_INFO>
<LICENSE_NO>1</LICENSE_NO>
<USER_ID>N/A</USER_ID>
</LICENSE_INFO>
<LICENCE_CONSTRAINT>
<MAX_USER>N/A</MAX_USER>
<MAX_MACHINE>N/A</MAX_MACHINE>
</LICENCE_CONSTRAINT>
<MACHINE_INFO>
<MACHINE_IP>1.2.3.4</MACHINE_IP>
<MACHINE_MAC>N/A</MACHINE_MAC>
</MACHINE_INFO>
</LICENSE>
you are creating your root element "LICENSE":
XmlElement root = doc.CreateElement("LICENSE");
but you're not appending it to doc.
Furthermore, you are appending to doc multiple times:
doc.AppendChild(subroot);
...
doc.AppendChild(subroot2);
...
doc.AppendChild(subroot3);
which is not possible since an XML document can have only 1 root.
Add your root element like so:
XmlElement root = doc.CreateElement("LICENSE");
doc.AppendChild(root);
And change every doc.AppendChild() lateron into root.AppendChild()
And I have to agree with L.B.: LINQ to XML is much easier for stuff like this (but that wasn't the question ;) )

Foreach loop XmlNodeList

Currently I have the following code:
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");
XmlNodeList tweets = xDoc.GetElementsByTagName("text");
foreach (int i in tweets)
{
if (tweets[i].InnerText.Length > 0)
{
MessageBox.Show(tweets[i].InnerText);
}
}
Which doesn't work, it gives me System.InvalidCastException on the foreach line.
The following code works perfectly (no foreach, the i is replaced with a zero):
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");
XmlNodeList tweets = xDoc.GetElementsByTagName("text");
if (tweets[0].InnerText.Length > 0)
{
MessageBox.Show(tweets[0].InnerText);
}
I know that there is already a marked answer, but you can do it like you did in your first try, you just need to replace the int with XmlNode
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");
XmlNodeList tweets = xDoc.GetElementsByTagName("text");
foreach (XmlNode i in tweets)
{
if (i.InnerText.Length > 0)
{
MessageBox.Show(i.InnerText);
}
}
tweets is a node list. I think that what you're trying to do is this:
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");
XmlNodeList tweets = xDoc.GetElementsByTagName("text");
for (int i = 0; i < tweets.Count; i++)
{
if (tweets[i].InnerText.Length > 0)
{
MessageBox.Show(tweets[i].InnerText);
}
}
It is not of Int type, That is the reason you are getting a casting exception. You can either replace int with the appropriate type or simply make use of type inference (implicitly typed variables) to handle this. Here i am using typeinference.by saying type as var, The compiler will understand it is of type of the iterator variable in tweets collection
foreach (var i in tweets)
{
if (i!=null)
{
string tweet= (((System.Xml.XmlElement)(i))).InnerText;
MessageBox.Show(tweet);
}
}
EDIT : With the Wonderful LINQtoXML, Your code can be rewritten like this.
string url = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter";
XElement elm = XElement.Load(url);
if (elm != null)
{
foreach (var status in elm.Elements("status"))
{
string tweet = status.Element("text").Value;
MessageBox.Show(ss);
}
}
All the answers seem to be a bit outdated Imperative examples so I will add a declarative one. This is not doing what the OP wanted but I'm sure you'll get the point.
public static List<System.Xml.XmlNode> toList(System.Xml.XmlNodeList nodelist){
List<System.Xml.XmlNode> nodes = new List<System.Xml.XmlNode>();
foreach (System.Xml.XmlNode node in nodelist)
{
nodes.Add(node);
}
return nodes;
}
public static ReadMeObject setXml(ReadMeObject readmeObject){
readmeObject.xmlDocument = new System.Xml.XmlDocument();
readmeObject.xmlDocument.LoadXml("<body>"+readmeObject.htmlStringContent+"</body>");
System.Xml.XmlNodeList images = readmeObject.xmlDocument.SelectNodes("//img");
Array.ForEach(
Functions.toList( images )
.Where((image) => image.Attributes != null)
.Where((image) => image.Attributes["src"] != null)
.Where((image) => image.Attributes["src"].Value != "")
.ToArray()
, (image) => {
Console.WriteLine(image.Attributes["src"].Value);
}
);
return readmeObject;
}
foreach (XmlNode node in tweets)
{
if (tweets[i].InnerText.Length > 0)
{
MessageBox.Show(tweets[node].InnerText);
}
}
I've changed the 'I', which you cannot use, to XmlNode, which selects a single line of your list.
You can loop through the Collection with .GetEnumerator()
this code is taken Microsoft Documentation :
XmlNodeList elemList = root.GetElementsByTagName("title");
IEnumerator ienum = elemList.GetEnumerator();
while (ienum.MoveNext()) {
XmlNode title = (XmlNode) ienum.Current;
Console.WriteLine(title.InnerText);
}
Use this simple extension method to iterate through XmlNodeList:
public static void ForEachXml<TXmlNode>(this XmlNodeList nodeList, Action<TXmlNode> action)
{
foreach (TXmlNode node in nodeList) action(node);
}
Method Call:
xDoc.GetElementsByTagName("text").ForEachXML<XmlNode>(tweet =>
{
if (tweet.InnerText.Length > 0)
MessageBox.Show(tweet.InnerText);
});

how to get xml nth element name in wpf

public partial class XML_3 : Window
{
public XML_3()
{
this.InitializeComponent();
XmlDocument doc = new XmlDocument();
doc.Load("D:/sample.xml");
XmlNodeList student_list = doc.GetElementsByTagName("Student");
foreach (XmlNode node in student_list)
{
XmlElement student = (XmlElement)node;
int element_count = student.ChildNodes.Count;
}
}
}
In above code.I can get the count of element except root element(Student). now the count is 3.
But i have to get 2ed element name(Kavi),it's attribute element name(ID) and it's child element name(FName,MName).
what should i do to get those stuff.
Please help me...
Use XDocument (why?):
var doc = XDocument.Parse(xml); // OR Load(...)
var nodeCount = doc.Elements().Count();
var secondNode = doc.Elements().Skip(1).First();
var studentName = secondNode.Name;
var studentId = secondNode.Attribute("ID").Value;
or (for your code):
var secondNode = student.ChildNodes[1] as XmlElement;
var studentName = secondNode.LocalName;
var studentId = secondNode.Attributes["ID"];
Added:
var secondNode = student.ChildNodes[1];
var fName =
secondNode.ChildNodes.Cast<XmlElement>().FirstOrDefault(x => x.LocalName == "FName").InnerText;
var mName =
secondNode.ChildNodes.Cast<XmlElement>().FirstOrDefault(x => x.LocalName == "MName").InnerText;
var studentId = secondNode.Attributes["ID"].Value;

Categories