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";}
Related
I am developing a universal windows app on windows 10 with Visual Studio 2015 and have a pretty large Xml structured like this:
<header id = "1">
<title>
some text
</title>
<question>
a question
</question>
<user_input>
<input1>
</input1>
<input2>
</input2>
</user_input>
</header>
<header id = "2">
<title>
some text
</title>
<question>
a question
</question>
<user_input>
<input1>
</input1>
<input2>
</input2>
</user_input>
</header>
...
This is repeating many times. There are parts that should never be changed (e.g. title, question). Now i want to write new elements into "ui", so it can be read again and shows the new content in texbox.
I use a FileStream and XmlDocument and XmlNodeList to read the Xml and show the content on textblocks:
path = "test.xml";
FileStream stream = new Filestream(path, FileMode.Open, FileAcces.Read);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(reader);
XmlNodeList node = xdoc.GetElementsByTagName("header");
textblock1.Text = node[0].Attributes["id"].Value;
textblock2.Text = node[i].ChildNode[1].InnerText;
....
I tried this to write into the Xml:
XDocument xdoc = XDocument.Load(path);
XElement ele = xdoc.Element("header");
ele.Add(new XElement("user_input",
new XElement("input1", newtext)));
xdoc.Save(path); <---- at this point there is an error
"Argument 1: cannot convert from 'string' to 'System.IO.Stream'"
My question is: how can i write the user input (some string) to the place I want it to be? The first input shall be written into header with id = 1 into user_input, the second into header id = "2" and so on. I already tried to load the xml with XDocument and write a new element with XElement, but it work at all.Is there something wrong with my xml? Or is it the function? Thank you in advance.
Firstly, the xml file cannot contain same roots, here you have two headers nodes but don't see a root node. So I add a root node for testing your xml file as follows
<?xml version="1.0" encoding="utf-8"?>
<Topics>
<header id = "1">
...
</header>
</Topics>
Secondly, this error
"Argument 1: cannot convert from 'string' to 'System.IO.Stream'"
xdoc.save(string) is not available in uwp, details you can see the version information of XDocument.Save method.
Thirdly, for this question
how can i write the user input (some string) to the place I want it to be?
we can insert value to special element by xpath or GetElementsByTagName method. In uwp, I recommend you use Windows.Data.Xml.Dom namespace instead of System.xml.Ling.
Here I wrote a demo for insert value to special place . And upload the demo to GitHub, you can download CXml for testing.
Mainly Code
private async void BtnXmlWrite_Click(object sender, RoutedEventArgs e)
{
String input1value = TxtInput.Text;
if (null != input1value && "" != input1value)
{
var value = doc.CreateTextNode(input1value);
//find input1 tag in header where id=1
var xpath = "//header[#id='1']/user_input/input1";
var input1nodes = doc.SelectNodes(xpath);
for (uint index = 0; index < input1nodes.Length; index++)
{
input1nodes.Item(index).AppendChild(value);
}
RichEditBoxSetMsg(ShowXMLResult, doc.GetXml(), true);
}
else
{
await new Windows.UI.Popups.MessageDialog("Please type in content in the box firstly.").ShowAsync();
}
}
More details you can reference XML dom Sample, XML and XPath.
I have an xml file and what I want to do is reverse its elements. I mean the first element should be last and last should be first. I want all the elements to reverse.
Ex. This should be
<Elements>
<Element1>
<Element2>
<Element3>
<Element4>
</ Elements>
This
<Elements>
<Element4>
<Element3>
<Element2>
<Element1>
</ Elements>
Can anyone help me achieve this?
Push them on a stack an then pop them off to rebuild it in reverse order. Do this recursively for every set of nested elements in the document.
Read them in and call .Reverse();
Alternatively use an .OrderByDescending()
Ok. Guys I've created a solution for reverse.
XmlDocument xd = new XmlDocument();
using (write = XmlWriter.Create(path2))
{
write.WriteStartDocument();
write.WriteStartElement("Customers");
write.WriteEndElement();
write.WriteEndDocument();
}
xd.Load(path2);
for (int i = count - 1; i >= 0; i--)
{
XmlNode node = xdoc.ChildNodes[1].ChildNodes[i];
//XComment com = new XComment("-------Reversed-------");
XmlNode xnode = xd.CreateNode(XmlNodeType.Element, "Customer", null);
XmlNode nodeId = xd.CreateElement("Id");
nodeId.InnerText = node.ChildNodes[0].InnerText;
XmlNode nodeName = xd.CreateElement("Name");
nodeName.InnerText = node.ChildNodes[1].InnerText;
XmlNode nodeAge = xd.CreateElement("Age");
nodeAge.InnerText = node.ChildNodes[2].InnerText;
xnode.AppendChild(nodeId);
xnode.AppendChild(nodeName);
xnode.AppendChild(nodeAge);
xd.DocumentElement.AppendChild(xnode);
xd.Save(path2);
}
The above code first loads the contents of the file whose elements have to be reversed. Then it creates a new file and stores the elements in that file in reverse order.
Hopefully this will help someone.
Ok so i have run into a bind with my work. I have a xml document i am trying to change. The value has to change every time a file has downloaded. So basically when file A finishes downloading version.xml has a id that i want to change from "0" to "1". Now with this i can finally set up my launcher the way i want it to be here the code that i have.
private void GetNextNodeID()
{
XmlDocument doc = new XmlDocument();
doc.Load(#"version.xml");
var x = doc.GetElementsByTagName("Product");
int Max = 0;
Max++
XmlElement newElement = doc.CreateElement("Product");
newElement.SetAttribute("id", Max.ToString());
doc.Save(#"version.xml");
}
also here is the xml document
<Table>
<Product>
<Product>0</Product>
<Product_name>Vitare</Product_name>
<Product_version>1.0.0.1</Product_version>
</Product>
</Table>
Now for some reason the code never messes with the xml file please help me figure out how to increment the value!!!!!!!!!
Thank you , Devin Magaro
Currently you're creating a new element using the document, but never actually adding it to the document. You're also trying to set an attribute where previously you had the text within the element itself.
Assuming you really do just want to update the element, I'd personally use LINQ to XML instead of XmlDocument:
var doc = XDocument.Load("version.xml");
// Single() ensures there's only one such element
var element = doc.Descendants("Product").Single();
int currentValue = (int) element;
element.SetValue(currentValue + 1);
doc.Save("version.xml");
If you want to update all Product elements, you should loop over doc.Descendants("Product") with a foreach loop.
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");
I have an xmldocument that i'm loading xml in to.
The xml looks like this:
<Table1>
<buyer_id>0</buyer_id>
<buyername>CompanyA</buyername>
<address1>123 Simpsons Dr.</address1>
<address2/>
<city>Springfield</city>
<state>ST</state>
<postalcode>12345</postalcode>
<eaddress/>
<phone/>
<fax/>
</Table1>
I'm looping through looking at each CompanyA entry and setting innertext accordingly. I'm using the following code to insert inner text into elements that meet the criteria:
XmlDocument dom = new XmlDocument();
dom.LoadXml(xmlString);
XmlNodeList elemList = dom.GetElementByTagName("Table1");
for(int i = 0; i < elemList.Count; i++)
{
if(dom.GetElementsByTagName("buyername").Item(i).InnerText.Contains("CompanyA")
{
dom.GetElementsByTagName("address1").Item(i).InnerText = "SomeInfo";
}
}
Using the above code, the value of address1(123 Simpsons Dr.) would be replaced by "SomeInfo". I would like to instead insert "SomeInfo" into the address2 element but when I try using:
dom.GetElementsByTagName("address2").Item(i).InnerText = "SomeInfo";
I get an error. I'm able to insert innertext into any element that already has a value but I cannot when the element is empty (such as <address2/>). Thoughts?
Use LINQ2XML.It's a complete replacement to other XML api's like the dirty old idiot XmlDocument
XElement doc=XElement.Load("yourXml.xml");
foreach(var elm in doc.Descendants("Table1"))
{
if(elm.Element("buyername").Value=="CompanyA")
elm.Element("address2").Value="SomeInfo";
}
doc.Save("yourXml.xml");
Check if the address2 xml tag is empty.
If yes , go to its parent and remove the tag then again add the same tag with value.
If no , assign the inner text to address2.
let me know if you need the code.
Use the SetElementValue method in LINQ to XML:
XDocument doc = XDocument.Load(FilePath); //replace with xml file path
IEnumerable<XElement> buyersList = doc.Descendants("Table1"); //get the table node.
var ele = (from buyer in buyersList
where buyer.Element("buyername").Value == "CompanyA"
select buyer).SingleOrDefault();
ele.SetElementValue("address1", "SomeInfo");
ele.SetElementValue("address2", "SomeInfo");
doc.Save(FilePath);
DEMO: http://ideone.com/Cf7YI