OneNote NavigateTo() responds with hrObjectDoesNotExist(0x80042014) when opening a page - c#

I am trying to programmatically open a one note page. I am doing that in C# and using OneNote2013. I iterate through the notebooks, section groups, sections and finally pages, get a page id and try to open the page with that PageId. But it throws a ObjectDoesNotExist exception. What am I doing wrong? Code Below (OpenOneNote() at the bottom.)
public class OneNoteInterface
{
static Application onenoteApp = new Application();
static XNamespace ns = null;
public static string GetPage(string notebookName, string sectionGroupName, string sectionName, string pageName, out string pageXml, out string sectionId)
{
var onenoteApp = new Application();
pageXml = "";
sectionId = "";
string notebookXml;
onenoteApp.GetHierarchy(null, HierarchyScope.hsChildren, out notebookXml);
var doc = XDocument.Parse(notebookXml);
var ns = doc.Root.Name.Namespace;
foreach (var notebookNode in from node in doc.Descendants(ns +
"Notebook")
select node)
{
//Console.WriteLine(notebookNode.Attribute("name").Value);
if (!notebookNode.Attribute("name").Value.Equals(notebookName))
continue;
string notebookID = notebookNode.Attribute("ID").Value;
onenoteApp.GetHierarchy(notebookID, HierarchyScope.hsChildren, out notebookXml);
Console.WriteLine(notebookXml);
doc = XDocument.Parse(notebookXml);
ns = doc.Root.Name.Namespace;
pageXml = "";
foreach (var sectionGroupNode in from node in doc.Descendants(ns + "SectionGroup") select node)
{
//Console.WriteLine(" " + sectionGroupNode.Attribute("name").Value);
if (sectionGroupNode.Attribute("name").Value.Equals(sectionGroupName))
{
string sectionGroupID = sectionGroupNode.Attribute("ID").Value;
onenoteApp.GetHierarchy(sectionGroupID, HierarchyScope.hsChildren, out notebookXml);
//Console.WriteLine(notebookXml);
doc = XDocument.Parse(notebookXml);
ns = doc.Root.Name.Namespace;
foreach (var sectionNode in from node in
doc.Descendants(ns + "Section")
select node)
{
Console.WriteLine(" " + sectionNode.Attribute("name").Value);
if (sectionNode.Attribute("name").Value.Equals(sectionName))
{
sectionId = sectionNode.Attribute("ID").Value;
onenoteApp.GetHierarchy(sectionId, HierarchyScope.hsChildren, out notebookXml);
//Console.WriteLine(notebookXml);
doc = XDocument.Parse(notebookXml);
ns = doc.Root.Name.Namespace;
foreach (var pageNode in from node in
doc.Descendants(ns + "Page")
select node)
{
//Console.WriteLine(" " + pageNode.Attribute("name").Value);
if (pageNode.Attribute("name").Value.Equals(pageName))
{
string pageId = pageNode.Attribute("ID").Value;
onenoteApp.GetPageContent(pageId, out pageXml, PageInfo.piAll);
doc = XDocument.Parse(pageXml);
//Console.WriteLine(pageXml);
return pageId;
}
}
return null;
}
}
return null;
}
}
return null;
}
return null;
}
static void GetNamespace()
{
string xml;
onenoteApp.GetHierarchy(null, HierarchyScope.hsNotebooks, out xml);
var doc = XDocument.Parse(xml);
ns = doc.Root.Name.Namespace;
}
static string GetObjectId(string parentId, HierarchyScope scope, string objectName)
{
string xml;
onenoteApp.GetHierarchy(parentId, scope, out xml);
var doc = XDocument.Parse(xml);
var nodeName = "";
switch (scope)
{
case (HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
case (HierarchyScope.hsPages): nodeName = "Page"; break;
case (HierarchyScope.hsSections): nodeName = "Section"; break;
default:
return null;
}
var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();
return node.Attribute("ID").Value;
}
public Boolean OpenOneNote(string notebookName, string sectionGroupName, string sectionName, string pageName)
{
string sectionId = "";
string pageXml = "";
string pageId = GetPage(notebookName, sectionGroupName, sectionName, pageName, out pageXml, out sectionId);
if (pageId != null)
{
onenoteApp.NavigateTo(pageId);
return true;
}
return false;
}

Related

Fragment cannot find variable from other Fragment

I have a problem. I have 2 Android.Support.V4.App.Fragments
In the first Framgent I use this code:
AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AgentSpinner.Adapter = AgentSpinnerAdapter;
foreach (string[] str in NamesArray)
{
string AgentId = str[0];
string Owner = str[1];
string Exchange = str[2];
string Remark = str[3];
AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark);
}
In the second Fragment I call this line:
dbValue = Fragment1.AgentSpinnerAdapter.GetItem(0);
But it says that AgentSpinnerAdapter is a nullreference, which is weird, because it get's filled. I have set the AgentSpinnerAdapter to Public static. Also in my MainActivity I first create Fragment1 and then Fragment2 like this:
Fragment1 = Fragment1.NewInstance();
Fragment2 = Fragment2.NewInstance();
What am I doing wrong?
UPDATE
Here is the full Fragment1.cs method
public void LoadAgentSpinner()
{
string json = "";
try
{
string html = string.Empty;
string url = "https://www.efy.nl/app/getagents.php";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
IgnoreBadCertificates();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
}
catch (Exception ex1)
{
try
{
WebClient client = new WebClient();
NameValueCollection fields = new NameValueCollection();
fields.Add("error", ex1.GetBaseException().ToString());
string url = "https://www.mywebsite.com";
IgnoreBadCertificates();
byte[] respBytes = client.UploadValues(url, fields);
string resp = client.Encoding.GetString(respBytes);
SelectedQuantity.Text = "";
SelectedLimit.Text = "";
}
catch (Exception ex2)
{
string exFullName = (ex2.GetType().FullName);
string ExceptionString = (ex2.GetBaseException().ToString());
}
}
//Parse json content
var jObject = JObject.Parse(json);
//Create Array from everything inside Node:"Coins"
var agentPropery = jObject["Agents"] as JArray;
//Create List to save Coin Data
agentList = new List<agent>();
//Find every value in Array: coinPropery
foreach (var property in agentPropery)
{
//Convert every value in Array to string
var propertyList = JsonConvert.DeserializeObject<List<agent>>(property.ToString());
//Add all strings to List
agentList.AddRange(propertyList);
}
//Get all the values from Name, and convert it to an Array
string[][] NamesArray = agentList.OrderBy(i => i.AgentId)
.Select(i => new string[] { i.AgentId.ToString(), i.Owner, i.Exchange, i.Remark })
.Distinct()
.ToArray();
AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AgentSpinner.Adapter = AgentSpinnerAdapter;
foreach (string[] str in NamesArray)
{
string AgentId = str[0];
string Owner = str[1];
string Exchange = str[2];
string Remark = str[3];
AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark); // format your string here
}
if(MainActivity.db.CheckExistTableSettings("Default Agent") == true)
{
string Value = MainActivity.db.SelectValueFromTableSettings("Default Agent");
int spinnerPosition = AgentSpinnerAdapter.GetPosition(Value);
AgentSpinner.SetSelection(spinnerPosition);
}
else
{
AgentSpinner.SetSelection(0);
}
}
In a few of my applications it's necessary to access the other fragments from my main Activity, so we do the following:
public class MainActivity : AppCompatActivity, BottomNavigationView.IOnNavigationItemSelectedListener
{
public static Dictionary<string, Fragment> FragmentList { get; set; }
private Fragment currentFragment = null;
private BottomNavigationView navigation;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout_mainactivity);
// create our fragments and initialise them early.
if (FragmentList == null)
{
FragmentList = new Dictionary<string, Fragment>
{
{ "main", MainFragment.NewInstance() },
{ "bugreport", BugReportFragment.NewInstance() },
{ "settings", SettingsFragment.NewInstance() }
};
}
navigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_nav);
navigation.SetOnNavigationItemSelectedListener(this);
navigation.SelectedItemId = Resource.Id.navigation_main;
}
public bool OnNavigationItemSelected(IMenuItem item)
{
if (!popAction)
{
navigationResourceStack.Push(item.ItemId);
}
switch (item.ItemId)
{
case Resource.Id.navigation_main:
currentFragment = FragmentList["main"];
break;
case Resource.Id.navigation_settings:
currentFragment = FragmentList["settings"];
break;
case Resource.Id.navigation_bugreport:
currentFragment = FragmentList["bugreport"];
break;
}
if (currentFragment == null)
{
return false;
}
else
{
FragmentManager.BeginTransaction().Replace(Resource.Id.frame_content, currentFragment).Commit();
return true;
}
}
}
What this means is you could do something like MainActivity.FragmentList["main"] and then call any public method on the actual initialized class because a pointer to it is stored within the dictionary.

Get string data Xpath

I need help to get data from the site. I use geckofx in my application. I want it to retrieve text data from the xpath location after loading the page
XPathResult xpathResult = geckoWebBrowser1.Document.EvaluateXPath("/html/body/table[3]/tbody/tr[1]/td[2]/a[1]");
IEnumerable<GeckoNode> foundNodes = xpathResult.GetNodes();
How to download data as text?
It looks like you are struggling to retrieve the text from the GeckoFX objects.
Here are a few calls and operations that should get you started:
//get by XPath
XPathResult xpathResult = _browser.Document.EvaluateXPath("//*[#id]/div/p[2]");
var foundNodes = xpathResult.GetNodes();
foreach (var node in foundNodes)
{
var x = node.TextContent; // get text text contained by this node (including children)
GeckoHtmlElement element = node as GeckoHtmlElement; //cast to access.. inner/outerHtml
string inner = element.InnerHtml;
string outer = element.OuterHtml;
//iterate child nodes
foreach (var child in node.ChildNodes)
{
}
}
//get by id
GeckoHtmlElement htmlElementById = _browser.Document.GetHtmlElementById("mw-content-text");
//get by tag
GeckoElementCollection byTag = _browser.Document.GetElementsByTagName("input");
foreach (var ele in byTag)
{
var y = ele.GetAttribute("value");
}
//get by class
var byClass = _browser.Document.GetElementsByClassName("input");
foreach (var node in byClass)
{
//...
}
//cast to a different object
var username = ((GeckoInputElement)_browser.Document.GetHtmlElementById("yourUsername")).Value;
//create new object from DomObject
var button = new GeckoButtonElement(_browser.Document.GetElementById("myBtn").DomObject);
public string extract(string xpath, string type)
{
string result = string.Empty;
GeckoHtmlElement elm = null;
GeckoWebBrowser wb = geckoWebBrowser1;//(GeckoWebBrowser)GetCurrentWB();
if (wb != null)
{
elm = GetElement(wb, xpath);
if (elm != null)
//UpdateUrlAbsolute(wb.Document, elm);
if (elm != null)
{
switch (type)
{
case "html":
result = elm.OuterHtml;
break;
case "text":
if (elm.GetType().Name == "GeckoTextAreaElement")
{
result = ((GeckoTextAreaElement)elm).Value;
}
else
{
result = elm.TextContent.Trim();
}
break;
case "value":
result = ((GeckoInputElement)elm).Value;
break;
default:
result = extractData(elm, type);
break;
}
}
}
return result;
}
private string extractData(GeckoHtmlElement ele, string attribute)
{
var result = string.Empty;
if (ele != null)
{
var tmp = ele.GetAttribute(attribute);
/*if (tmp == null)
{
tmp = extractData(ele.Parent, attribute);
}*/
if (tmp != null)
result = tmp.Trim();
}
return result;
}
private object GetCurrentWB()
{
if (tabControl1.SelectedTab != null)
{
if(tabControl1.SelectedTab.Controls.Count > 0)
//if (tabControl1.SelectedTab.Controls.Count > 0)
{
Control ctr = tabControl1.SelectedTab.Controls[0];
if (ctr != null)
{
return ctr as object;
}
}
}
return null;
}
private GeckoHtmlElement GetElement(GeckoWebBrowser wb, string xpath)
{
GeckoHtmlElement elm = null;
if (xpath.StartsWith("/"))
{
if (xpath.Contains("#class") || xpath.Contains("#data-type"))
{
var html = GetHtmlFromGeckoDocument(wb.Document);
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var node = doc.DocumentNode.SelectSingleNode(xpath);
if (node != null)
{
var currentXpath = "/" + node.XPath;
elm = (GeckoHtmlElement)wb.Document.EvaluateXPath(currentXpath).GetNodes().FirstOrDefault();
}
}
else
{
elm = (GeckoHtmlElement)wb.Document.EvaluateXPath(xpath).GetNodes().FirstOrDefault();
}
}
else
{
elm = (GeckoHtmlElement)wb.Document.GetElementById(xpath);
}
return elm;
}
private string GetHtmlFromGeckoDocument(GeckoDocument doc)
{
var result = string.Empty;
GeckoHtmlElement element = null;
var geckoDomElement = doc.DocumentElement;
if (geckoDomElement is GeckoHtmlElement)
{
element = (GeckoHtmlElement)geckoDomElement;
result = element.InnerHtml;
}
return result;
}
private void button5_Click(object sender, EventArgs e)
{
var text = extract("/html/body/table[3]/tbody/tr[1]/td[2]/a[2]", "text");
MessageBox.Show(text);
}
I also insert the code from which I used a little longer code but it also works. maybe someone will need it. The creator of the code is Đinh Công Thắng, Web Automation App,
Regards

Instagram API: How to insert all user media in c# asp.net mvc?

I am trying the get all user media from the instagram api and store into database but how can do that i don't know. i am write the code but using this code just add one media in the database. any one have the idea then please let me know how can do that. here below list the my code.
This is my C# method :
public string makePostFromInstagram()
{
var serializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
var nodes1 = serializer1.Deserialize<dynamic>(GetData(strInstagramUserId));
foreach (var date in nodes1)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
int userCount = 0;
foreach (var post in thisNode)
{
if (thisNode[userCount]["username"] == strInstagramUserId)
{
id = thisNode[userCount]["id"].ToString();
}
userCount++;
}
}
}
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, object> csObj = serializer.Deserialize<Dictionary<string, object>>(GetRecentPost(id, accessToken));
int length = ((ArrayList)csObj["data"]).Count;
var nodes = serializer.Deserialize<dynamic>(GetRecentPost(id, accessToken));
foreach (var date in nodes)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
foreach (var post in thisNode)
{
UsersOnInstagram objUserInsta = new UsersOnInstagram();
string result = null;
//here i am add just one image so i want to here add multiple image insert
if (post["type"] == "image")
result = UsersOnInstagram.addInstagramPost(strPtId, HttpUtility.UrlEncode(post["caption"]["text"]), post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), null, post["type"]);
else if (post["type"] == "video")
result = objUserInsta.addInstagramPost(HttpUtility.UrlEncode(post["caption"]["text"]), strPtId, post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), post["videos"]["standard_resolution"]["url"], post["type"]);
}
}
}
Response.End();
}
this is my api method :
public static string GetRecentPost(string instagramaccessid, string instagramaccesstoken)
{
Double MAX_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-1));
Double MIN_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-2));
string url = "https://api.instagram.com/v1/users/" + instagramaccessid + "/media/recent?access_token=" + instagramaccesstoken + "&min_timestamp=" + MIN_TIMESTAMP + "&maz_timestamp=" + MAX_TIMESTAMP;
var webClient = new System.Net.WebClient();
string d = webClient.DownloadString(url);
return d;
}
any one know how can do that please let me know.

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 ;) )

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