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.
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 am fairly new to programming and need to check a Single node in a XML file for a certain value and need to check if that value is correct.
I need to validate these 3 Nodes in 3 different classes:
<RunCodeAnalysis>true</RunCodeAnalysis>
I need to select this specific node from a xml file and need to check if the value of the node is true, i hope to get some help with the validation if the value is acutally true
private void CodeAnalysisEnabled(XDocument xmlDoc)
{
var codeAnalysis = from doc in xmlDoc.Root?.Descendants("RunCodeAnalysis") select doc;
foreach (var codeAnalysisNode in codeAnalysis)
{
codeAnalysisNode.Value = "true";
}
}
Load XML and use XPath to search for tags:
var document = new XmlDocument();
document.Load(fileName);
var root = document.DocumentElement
var nodes = root.SelectNodes("//RunCodeAnalysis");
This sample selects all RunCodeAnalysis nodes from XML. Using XPath you can select exactly what you want. Check this MSDN article.
Although there are many answers to this topic, I couldn't find one that worked in my case.
The app opens the xml file to add new entries from a list, but prevents duplicates. I don't know how to check (using Linq) if the item is already in the xml
<!-- XML File sample -->
<?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item>
<Text>AUDI</Text>
</Item>
<Item>
<Text>BMW</Text>
</Item>
</Items>
and this is the code. (I left out trim, uppercase, etc for simplicity)
The problem is in the result var, it always return false.
XDocument doc = XDocument.Load(#filePath);
for (int i = 0; i < items.Count; i++)
{
var result = doc.Descendants("Item").Any(x => x.Element("Text").ToString().Equals(items[i]);
if (! result)
{
}
doc.Save(#filePath);
Your problem is :
x.Element("Text").ToString()
To get the string inside the Text node use .Value
Like so:
XDocument doc = XDocument.Load(#filePath);
for (int i = 0; i < items.Count; i++)
{
var result = doc.Descendants("Item").Any(x => x.Element("Text").Value.Equals(items[i]));
if (!result)
{
}
}
doc.Save(#filePath);
I believe you're misinterpreting the format of your XML.. You're looking to match the InnerXml of the Text element which you never do here. So you need to move from Root -> Items -> Item -> Text -> Value which isn't exactly what's happening with your code.
So at a minimum you need to use the Value reference on the Text element (x.Element("Text").Value). Also, I think your call to Descendants directly returns the Text elements so I would recommend inspecting the IEnum after that and confirming what level of the xml you're at at that point. I haven't used that method but my understanding is that it gives you descendants of the xpath you provide which means it gives you Text elements. If that is the case change that string to "Items" and you'll be good to go.
I am trying to extract some SQL data to XML from a Microsoft Dynamics environment, I am currently using LINQ To XML in C# to read and write to my XML files. One piece of data I need is from a view called SECURITYSUBROLE. Looking at the structure of this view shows that there is a column also named SECURITYSUBROLE. My normal method of extraction has given me this XML.
<SECURITYSUBROLE>
<SECURITYROLE>886301</SECURITYROLE>
<SECURITYSUBROLE>886317</SECURITYSUBROLE>
<VALIDFROM>1900-01-01T00:00:00-06:00</VALIDFROM>
<VALIDFROMTZID>0</VALIDFROMTZID>
<VALIDTO>1900-01-01T00:00:00-06:00</VALIDTO>
<VALIDTOTZID>0</VALIDTOTZID>
<RECVERSION>1</RECVERSION>
<RECID>886317</RECID>
</SECURITYSUBROLE>
When I try to import this data later on, I am getting errors because the parent XML node has the same name as a child node. Here is a snippet of the import method:
XmlReaderSettings settings = new XmlReaderSettings();
settings.CheckCharacters = false;
XmlReader reader = XmlReader.Create(path, settings);
reader.MoveToContent();
int count = 1;
List<XElement> xmlSubset = new List<XElement>();
while (reader.ReadToFollowing(xmlTag))
{
if (count % 1000 == 0)
{
xmlSubset.Add(XElement.Load(reader.ReadSubtree()));
XDocument xmlTemp = new XDocument(new XElement(xmlTag));
foreach (XElement elem in xmlSubset)
{
xmlTemp.Root.Add(elem);
}
xmlSubset = new List<XElement>();
ImportTableByName(connectionString, tableName, xmlTemp);
count = 1;
}
else
{
xmlSubset.Add(XElement.Load(reader.ReadSubtree()));
count++;
}
}
}
It's currently failing on the XmlReader.ReadToFollowing, where it doesn't know where to go next because of the name confusion. So my question has two parts:
1) Is there some better way to be extracting this data other than to XML?
2) Is there a way through LINQ To XML that I can somehow differentiate between the parent and child nodes named exactly the same?
To get the elements (in your case) for SECURITYSUBROLE you can check to see if the element's have children:
XElement root = XElement.Load(path);
var subroles = root.Descendants("SECURITYSUBROLE") // all subroles
.Where(x => !x.HasElements); // only subroles without children
I'm going to suggest a different approach:
1) VS2013 (possibly earlier versions too) has a function to create a class from an XML source. So get one of your XML files and copy the content to your clipboard. Then in a new class file Edit --> Paste Special --> Paste XML as Classes
2) Look into XmlSerialization which will allow you to convert an XML file into an in memory object with a strongly typed class.
XmlSerializer s = new XmlSerializer(yourNewClassTYPE);
TextReader r = new StreamReader(XmlFileLocation);
var dataFromYourXmlAsAStronglyTypedClass = (yourNewlyClassTYPE) s.Deserialize(r);
r.Close();
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