Good day everyone. I would like to ask for help with my code. I have here an XML document containing the following.
<?xml version="1.0" encoding="utf-8" ?>
<TechnicalReport>
<Data quantity = "2" description ="myDesc" findings = "none" actiontaken = "none" />
</TechnicalReport>
What I would like to do here is to add another child node inside the . I have searched for so many websites about my problem but to no avail. For example, I will add another node, say:
<?xml version="1.0" encoding="utf-8" ?>
<TechnicalReport>
<Data quantity = "2" description ="myDesc" findings = "none" actiontaken = "none" />
<Data quantity = "3" description ="myDesc2" findings = "none2" actiontaken = "none3" />
</TechnicalReport>
I have successfully compiled and loaded the XML file into a Repeater control using an XMLDataSource, but when I do an insert from my form, the Repeater control does not update its contents, and even my XML file also does not update.
Here's my C# code:
public void AddNewRecord()
{
//Load XML Schema
XmlDocument originalXml = new XmlDocument();
originalXml.Load(Server.MapPath("xmlTechReportDetails.xml"));
//Create the node name Technical Report
XmlNode TechReport = originalXml.SelectSingleNode("TechnicalReport");
XmlNode Data = originalXml.CreateNode(XmlNodeType.Element, "Data", null);
//Insert quantity
XmlAttribute quantity = originalXml.CreateAttribute("quantity");
quantity.Value = txtQty.Text;
//Insert description
XmlAttribute description = originalXml.CreateAttribute("description");
description.Value = txtDescription.Text;
//Insert findings
XmlAttribute findings = originalXml.CreateAttribute("findings");
findings.Value = txtFindings.Text;
//Insert actions taken.
XmlAttribute actionTaken = originalXml.CreateAttribute("actiontaken");
actionTaken.Value = txtAction.Text;
Data.Attributes.Append(quantity);
Data.Attributes.Append(description);
Data.Attributes.Append(findings);
Data.Attributes.Append(actionTaken);
TechReport.AppendChild(Data);
}
Please help.
Try adding this at the end of your method:
originalXml.Save(Server.MapPath("xmlTechReportDetails.xml"));
I think it's because you did not save the file. That's why your changes are not retained.
Instead of this code:
//Create the node name Technical Report
XmlNode TechReport = originalXml.SelectSingleNode("TechnicalReport");
Use this code
XmlNodeList nodeList = originalXml.GetElementsByTagName("connectionStrings");
Related
I am trying to update my grid in edit mode using xml but I am not able to do it.
I am able to edit only one element but dont know how to edit more than one
my xml file looks like below
<CATALOG>
<CD>
<ID>1</ID>
<Application>Dot Net</Application>
<status>Available</status>
<LastUpdate>02-07-2017</LastUpdate>
<Comments>The Rox for July has been loaded</Comments>
</CD>
<CD>
<ID>2</ID>
<Application>JFORWBK</Application>
<status>Available</status>
<LastUpdate>05-07-2017</LastUpdate>
<Comments>DeLorean data has been loaded</Comments>
</CD>
<CD>
<ID>3</ID>
<Application>Codepress</Application>
<status>Open for Input</status>
<LastUpdate>06-07-2017</LastUpdate>
<Comments>The Rox for July has been loaded</Comments>
</CD>
</catalog>
When i open the data in grid in edit mode basis of id than I am able to update on single element
How can i update all the element in one time if i have the value in hidden field.
I am able to update my xml element on basis of id.I am only able to update one element in 1 time..
Code as follows:
ID = Request.QueryString["sID"];
XmlDocument xmlDoc = new XmlDocument();
string filepathsUpdate = Server.MapPath("Action.xml");
xmlDoc.Load(filepathsUpdate);
XmlNode node = xmlDoc.SelectSingleNode("/CATALOG/CD[ID=" + ID + "]/Action");
node.InnerText = ssplit[0];
xmlDoc.Save(filepathsUpdate);
Now How do it update ,, and comments in edit mode on click of update button in C# on server side.
Why don't you use a loop to update them one by one like.
Put you all hidden field values in Ids list. Then use a loop to update the XML.
List<int> Ids = new List<int>();
Ids.Add(1);
for (int i = 0; i < Ids.Count; i++)
{
ID = Request.QueryString["sID"];
XmlDocument xmlDoc = new XmlDocument();
string filepathsUpdate = Server.MapPath("Action.xml");
xmlDoc.Load(filepathsUpdate);
XmlNode node = xmlDoc.SelectSingleNode("/CATALOG/CD[ID=" + Ids[i].ToString() + "]/Action");
node.InnerText = ssplit[0];
xmlDoc.Save(filepathsUpdate);
}
In LINQ to XML it is pretty straightforward:
var id = Request.QueryString["sID"];
XDocument doc = XDocument.Load("Action.xml");
var catalogDescendants = doc.Descendants("CATALOG");
foreach (var cd in catalogDescendants)
{
//you can update the id here for whatever you want
cd.Element("ID").Value = id;
}
You could use the XmlNodeList and iterate for each XmlNode within that list and perform an update.
If memory serves it ought to be along the lines of
foreach(XmlNode node in XmlDoc.selectNodes("nodename")){node.innerText = "updated value here";}
I want to update the node in xml file.I want to check the loginid and increment it by 1. I have been trying something like this but the xml file is not getting updated.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("tempLogonoff.xml");
XmlNode node = xmlDoc.SelectSingleNode("//tblTemp/Login/LoginId");
node.Attributes[0].Value = (LoginId + 1).ToString();
xAnd I have a following Xml File:mlDoc.Save("tempLogonoff.xml");
And I have following Xml code
<?xml version="1.0" encoding="utf-8"?>
<tblTemp>
<Login>
<LoginId>3</LoginId>
<AgentId>2</AgentId>
<OracleId>763887</OracleId>
</Login>
<Login>
<LoginId>2</LoginId>
<AgentId>1</AgentId>
<OracleId>763602</OracleId>
</Login>
</tblTemp>
So if my agentId changes,that login id should change.
I am getting an exception-"The index being passed in is out of range."Can you please help me on this same.
You could try setting the InnerText of the node and not its attributes (as it doesn't have any):
XmlNode node = xmlDoc.SelectSingleNode("//tblTemp/Login/LoginId");
node.InnerText = (LoginId + 1).ToString();
Using C# I have an XML file like
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account>
<name>Jani</name>
</Account>
</root>
and I also have a function to read the name node as:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("lib//user.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
label1.Text = name.ToString();
but I am getting index out of range error as:
Why is this happening?
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
node is your root node. Which looks like this:
<root>
How many attributes does it have? None, as it turns out. An attribute in XML is one of these bar="baz" things:
<foo bar="baz">
node.Attributes[0] refers to the first attribute. There is no first attribute, there's no second attribute -- you didn't use attributes in this XML at all. Hence, that's out of range. There's no first item in an empty collection.
What you want is an element named name, which is farther down inside your XML tree.
Probably this:
var node = xmlDoc.DocumentElement.SelectSingleNode("/root/Account/name");
And then you'll want to look at node.InnerText to get "Jani" out of it.
You are trying to read node.Attributes[0].Value but there is no attribtues in your sample XML file. Not sure of the exact syntax but it should probably be closer to node.Value
As mentioned by other answers, your current XML does not have attributes.
private void DoIt()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
//string name = node.Attributes[0].Value;
string name = node["Account"].InnerText;
}
If your XML did have attributes
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account name="Jani" />
</root>
Then you could do this:
private void DoItAgain()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data2.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node["Account"].Attributes[0].Value;
}
I have an xml document like as shown below.
<?xml version="1.0" encoding="UTF-8"?>
<Projects>
<Project>
<ProjectNo>111</ProjectNo>
<Client/>
<Responsible/>
<Participants/>
<Date>13-11-2015</Date>
</Project>
<Transfers ID="1">
<SampleID>1</SampleID>
<SampleNo>222</SampleNo>
<ChamberNo>p111</ChamberNo>
</Transfers>
<Transfers ID="2">
<SampleID>2</SampleID>
<SampleNo>32</SampleNo>
<ChamberNo>p311</ChamberNo>
</Transfers>
<Transfers ID="3">
<SampleID>3</SampleID>
<SampleNo>42</SampleNo>
<ChamberNo>p211</ChamberNo>
</Transfers>
</Projects>
I am trying to read nodes and its elements like this
XDocument xmlDocument = XDocument.Load(GlobalVariables.XmlPath + "\\" + GlobalVariables.ProjectID + ".xml");
var project = from p in xmlDocument.Descendants("Project")
select new Project
{
ProjectNo = p.Element("ProjectNo").Value,
Client = p.Element("Client").Value,
ProjectResponsible = p.Element("Responsible").Value,
Participants = p.Element("Participants").Value,
Date = Convert.ToDateTime(p.Element("Date").Value).Date,
};
var Samples = (from s in xmlDocument.Descendants("Transfers")
select new Sample
{
SampleID = Convert.ToInt32(s.Element("SampleID").Value),
SampleNo = s.Element("SampleNo").Value,
ChamberNo = s.Element("ChamberNo").Value,
}
);
int SamplesNo = Samples.Count();
CreateWordDocument(project, Samples, SamplesNo);
I am able to read nodes and its elements at first time but if i edit values in xml file and try to read again then i am getting error "NullreferenceException was unhandled" Object reference not set to an instance of an object.
What might be the problem and how to rectify it?
Any suggestions?
I have Data.xml:
<?xml version="1.0" encoding="utf-8" ?>
<data>
<album>
<slide title="Autum Leaves"
description="Leaves from the fall of 1986"
source="images/Autumn Leaves.jpg"
thumbnail="images/Autumn Leaves_thumb.jpg" />
<slide title="Creek"
description="Creek in Alaska"
source="images/Creek.jpg"
thumbnail="images/Creek_thumb.jpg" />
</album>
</data>
I'd like to be able to edit the attributes of each Slide node via GridView (that has a "Select" column added.) And so far I have:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedIndex = GridView1.SelectedIndex;
LoadXmlData(selectedIndex);
}
private void LoadXmlData(int selectedIndex)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(MapPath(#"..\photo_gallery\Data.xml"));
XmlNodeList nodelist = xmldoc.DocumentElement.ChildNodes;
XmlNode xmlnode = nodelist.Item(selectedIndex);
titleTextBox.Text = xmlnode.Attributes["title"].InnerText;
descriptionTextBox.Text = xmlnode.Attributes["description"].InnerText;
sourceTextBox.Text = xmlnode.Attributes["source"].InnerText;
thumbTextBox.Text = xmlnode.Attributes["thumbnail"].InnerText;
}
The code for LoadXmlData is just a guess on my part - I'm new to working with xml in this way. I'd like have the user to slected the row from the gridview, then populate a set of text boxes with each slide attributed for updating back to the Data.xml file.
The error I'm getting is Object reference not set to an instance of an object" at the line: titleTextBox.Text = xmlnode.Attributes["#title"].InnerText;
so I'm not reaching the attribute "title" of the slide node. Thanks for any ideas you may have.
Well yes - given your XML, the xmldoc.DocumentElement.ChildNodes; statement will give you exactly one node - the <album> node - and it doesn't have any attribute called ["title"].
You need to
change the way you select your nodes; the xmldoc.DocumentElement corresponds to the <data> node, and it's .ChildNodes collection will include all the direct child nodes - which in this case is the one and only <album> node - nothing else.
check for existence! (and not just assume it works...)
Try this:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(MapPath(#"..\photo_gallery\Data.xml"));
XmlNodeList nodelist = xmldoc.SelectNodes("/data/album/slide");
foreach(XmlNode xmlnode in nodelist)
{
if(xmlnode.Attributes["title"] != null
titleTextBox.Text = xmlnode.Attributes["title"].InnerText;
if(xmlnode.Attributes["description"] != null
descriptionTextBox.Text = xmlnode.Attributes["description"].InnerText;
if(xmlnode.Attributes["source"] != null
sourceTextBox.Text = xmlnode.Attributes["source"].InnerText;
if(xmlnode.Attributes["thumbnail"] != null
thumbTextBox.Text = xmlnode.Attributes["thumbnail"].InnerText;
}
#title is a XPath call for attributes, i.e. "//slide['#title']"
XmlNode.Attributes holds attributes just by name - title, i.e. node.Attributes["title"]