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.
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";}
How can I read an XML attribute using C#'s XmlDocument?
I have an XML file which looks somewhat like this:
<?xml version="1.0" encoding="utf-8" ?>
<MyConfiguration xmlns="http://tempuri.org/myOwnSchema.xsd" SuperNumber="1" SuperString="whipcream">
<Other stuff />
</MyConfiguration>
How would I read the XML attributes SuperNumber and SuperString?
Currently I'm using XmlDocument, and I get the values in between using XmlDocument's GetElementsByTagName() and that works really well. I just can't figure out how to get the attributes?
XmlNodeList elemList = doc.GetElementsByTagName(...);
for (int i = 0; i < elemList.Count; i++)
{
string attrVal = elemList[i].Attributes["SuperString"].Value;
}
You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.
Then the code would be something similar to
string attrVal = doc.SelectSingleNode("/MyConfiguration/#SuperNumber").Value;
Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.
You can migrate to XDocument instead of XmlDocument and then use Linq if you prefer that syntax. Something like:
var q = (from myConfig in xDoc.Elements("MyConfiguration")
select myConfig.Attribute("SuperString").Value)
.First();
I have an Xml File books.xml
<ParameterDBConfig>
<ID Definition="1" />
</ParameterDBConfig>
Program:
XmlDocument doc = new XmlDocument();
doc.Load("D:/siva/books.xml");
XmlNodeList elemList = doc.GetElementsByTagName("ID");
for (int i = 0; i < elemList.Count; i++)
{
string attrVal = elemList[i].Attributes["Definition"].Value;
}
Now, attrVal has the value of ID.
XmlDocument.Attributes perhaps? (Which has a method GetNamedItem that will presumably do what you want, although I've always just iterated the attribute collection)
Assuming your example document is in the string variable doc
> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1
If your XML contains namespaces, then you can do the following in order to obtain the value of an attribute:
var xmlDoc = new XmlDocument();
// content is your XML as string
xmlDoc.LoadXml(content);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
// make sure the namespace identifier, URN in this case, matches what you have in your XML
nsmgr.AddNamespace("ns", "urn:oasis:names:tc:SAML:2.0:protocol");
// get the value of Destination attribute from within the Response node with a prefix who's identifier is "urn:oasis:names:tc:SAML:2.0:protocol" using XPath
var str = xmlDoc.SelectSingleNode("/ns:Response/#Destination", nsmgr);
if (str != null)
{
Console.WriteLine(str.Value);
}
More on XML namespaces here and here.
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
I have a request that returns a large xml file. I have the file in a XmlDocument type in my application. From that Doc how can I read an element like this:
<gphoto:videostatus>final</gphoto:videostatus>
I would like to pull that value final from that element. Also If i have multiple elements as well, can I pull that into a list? thanks for any advice.
If you already have an XmlDocument then you can use the function GetElementsByTagName() to create an XmlNodeList that can be accessed similar to an array.
http://msdn.microsoft.com/en-us/library/dc0c9ekk.aspx
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
//Display all the book titles.
XmlNodeList elemList = doc.GetElementsByTagName("title");
for (int i=0; i < elemList.Count; i++)
{
Console.WriteLine(elemList[i].InnerXml);
}
You can select nodes using XPath and SelectSingleNode SelectNodes. Look at http://www.codeproject.com/Articles/9494/Manipulate-XML-data-with-XPath-and-XmlDocument-C for examples. Then you can use for example InnerText to get final. Maybe you need to work with namespaces (gphoto). The //videostatus would select all videostatus elements
You can try using LINQ
XNamespace ns = XNamespace.Get(""); //use the xmnls namespace here
XElement element = XElement.Load(""); // xml file path
var result = element.Descendants(ns + "videostatus")
.Select(o =>o.Value).ToList();
foreach(var values in value)
{
}
Thanks
Deepu
We are interested in finding maximum number of attributes a node has in a XML document. My code is below using C#:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"C:\ABC.xml");
XmlNode root = xmlDoc.DocumentElement;
int nodeAttrCount = 0;
foreach (XmlNode node in root)
if (nodeAttrCount < node.Attributes.Count)
nodeAttrCount = node.Attributes.Count;
We are interested is: do we have any thing better than this. Like any method or property which give us the same result or anyother option.
You can also use LINQ to XML:
XElement el = XElement.Load("MyXML.xml");
int maxAttr = el.DescendantNodesAndSelf().OfType<XElement>().Max(x => x.Attributes().Count());
The above code traverses all the xml nodes (it works with nested nodes too) and get the maximum number of attributes.
For .net 2.0:
XmlDocument doc = new XmlDocument();
doc.Load("MyXML.xml");
int max = 0;
foreach (XmlNode xmlNode in doc.SelectNodes("//*"))
if (max < node.Attributes.Count)
max = node.Attributes.Count;
This is basically the same as your solution;
the main difference is that it considers all nodes at every nesting level (using XPath navigation).
This is three lines of code for a fairly niche requirement. I wouldn't expect this to already exist in the .NET framework.
Your foreach loop looks fine. Are you sure you want to only look at the root elements, and not recurse inside the document?