I have the following code which creates an XML file with a bunch of order information. I'd like to be able to update an entry in this XML file instead of deleting everything and re-adding everything again.
I know I can do this:
xElement.Attribute(attribute).Value = value;
But that will change every attribute with the same name as attribute holds. How can I only change the value of something when the entry's Id equals "jason", for example? Would I need to Load the XML file, iterate over the entire file until it finds a match for the attribute I want to change, then change it, and then save the file again?
Any help/suggestions are greatly appreciated.
XElement xElement;
xElement = new XElement("Orders");
XElement element = new XElement(
"Order",
new XAttribute("Id", CustomId),
new XAttribute("Quantity", Quantity),
new XAttribute("PartNo", PartNo),
new XAttribute("Description", Description),
new XAttribute("Discount", Discount),
new XAttribute("Freight", Freight),
new XAttribute("UnitValue", UnitValue),
new XAttribute("LineTotal", LineTotal)
);
xElement.Add(element);
xElement.Save(PartNo + ".xml");
Here's what my XML file looks like:
<?xml version="1.0" encoding="utf-8"?>
<Orders>
<Order Id="V45Y7B458B" Quantity="2" PartNo="5VNB98" Description="New Custom Item Description" Discount="2.00" Freight="2.90" UnitValue="27.88" LineTotal="25.09" />
<Order Id="jason" Quantity="2" PartNo="jason" Description="New Custom Item Description" Discount="2.00" Freight="2.90" UnitValue="27.88" LineTotal="25.09" />
</Orders>
Something like this:
var doc = XDocument.Load("FileName.xml");
var element = doc.Descendants("Order")
.Where(arg => arg.Attribute("Id").Value == "jason")
.Single();
element.Attribute("Quantity").Value = "3";
doc.Save("FileName.xml");
First you need to search for the element that you want to update. If you find it, do the update. Just remember to save the XDocument back to the file when you're done.
XDocument doc = ...;
var jason = doc
.Descendants("Order")
.Where(order => order.Attribute("Id").Value == "jason") // find "jason"
.SingleOrDefault();
if (jason != null) // if found,
{
// update something
jason.Attribute("Quantity").SetValue(20);
}
doc.Save(...); // save if necessary
Since you created the XML file, you know the root element of the XML so you can use this code to get the particular element you want:
TaxonPath = XElement.Parse(xml as string);
txtSource.Text = FindGetElementValue(TaxonPath, TaxonPathElement.Source);
XElement FindGetElementValue(XElement tree,String elementname)
{
return tree.Descendants(elementName).FirstOrDefault();
}
With this, you can get the element, check its value, and change it as you desire.
Related
I have a XML file like this:
<?xml version="1.0" encoding="utf-8"?>
<ApplicationConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ua="http://opcfoundation.org/UA/2008/02/Types.xsd" xmlns="http://opcfoundation.org/UA/SDK/Configuration.xsd">
<ServerConfiguration>
<SecurityPolicies>
<ServerSecurityPolicy>
<SecurityMode>None_1</SecurityMode>
</ServerSecurityPolicy>
</SecurityPolicies>
</ServerConfiguration>
</ApplicationConfiguration>
What I want is to add more node named ServerSecurityPolicy by code.
Then I use this code:
string docaddress = "D:\\abc.xml";
XDocument doc = XDocument.Load(docaddress);
var root = doc.Root;
var these = root.Descendants().Where(p => p.Name.LocalName == "SecurityPolicies");
XElement addelement = new XElement("ServerSecurityPolicy");
addelement.Add(new XElement("SecurityMode", "None_1"));
foreach (var elem in these)
{
elem.Add(addelement);
}
doc.Save(docaddress);
It actually works, but the newly added node is something like this:
<ServerSecurityPolicy xmlns="">
<SecurityMode>None_1</SecurityMode>
</ServerSecurityPolicy>
I don't want the attribute "xmlns", then I try to delete it by something like this:
var these2 = root.Descendants().Where(p => p.Name.LocalName == "ServerSecurityPolicy");
foreach (var elem in these2)
{
label2.Text += elem.Attribute("xmlns").Name.LocalName;
elem.Attribute("xmlns").Remove();
}
The label2.Text shows "xmlnsxmlnsxmlsn..." so that I think the elem.Attribute("xmlns") has pointed to the attributes I want to delete, but the Remove() not work.
Can you suggest me some ways to delete the attribute or add node without attribute?
Thank you
The reason you're getting an empty attribute - which xmlns="" refers to - is because your document's root node belongs to the namespace xsi. When you're adding a node without a namespace - as you're doing in your example - you're not actually binding it to the xsi namespace.
To make your node part of the root namespace, replace
new XElement("ServerSecurityPolicy")
with
new XElement("ServerSecurityPolicy",
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"))
The problem is that the element you want to create is actually in the http://opcfoundation.org/UA/SDK/Configuration.xsd namespace, which is the default for the document because of this part of the root element:
xmlns="http://opcfoundation.org/UA/SDK/Configuration.xsd"
You can create an element in that namespace easily:
XNamespace configNs = "http://opcfoundation.org/UA/SDK/Configuration.xsd";
var these = root.Descendants(configNs + "ServerSecurityPolicy");
When you add that to your document, you'll find it won't add the xmlns="" part, which was present because you were adding an element without a namespace.
I'd also suggest using the namespace to find elements too:
XNamespace configNs = "http://opcfoundation.org/UA/SDK/Configuration.xsd";
var these = root.Descendants(configNs + "SecurityPolicies");
That's much cleaner than just using the local name, in my view.
What I'm trying to do is get data from my XML file which has been merged with two others and selected each venue from that file and try to add the value to a list so I can manipulate it further.
This is one of my XML files
<?xml version="1.0" encoding="utf-8" ?>
<Funrun>
<Venue name="Roker Park">
<Runner charity="Cancer Research">
<Firstname>Roger</Firstname>
<Lastname>Malibu</Lastname>
<Sponsorship>550</Sponsorship>
</Runner>
<Runner charity="Arthritis UK">
<Firstname>Adam</Firstname>
<Lastname>White</Lastname>
<Sponsorship>340</Sponsorship>
</Runner>
</Venue>
</Funrun >
I need to be able to select the venue name and save it to a list. This is what I've got so far:
List<string> VenueNames = new List<string>();
var doc = XDocument.Load("XMLFile1.xml");
var doc2 = XDocument.Load("XMLFile2.xml");
var doc3 = XDocument.Load("XMLFile3.xml");
var combinedUnique = doc.Descendants("Venue")
.Union(doc2.Descendants("Venue"))
.Union(doc3.Descendants("Venue"));
foreach (var venuename in combinedUnique.Elements("Venue"))
{
VenueNames.Add(venuename.Attribute("name").Value));
}
The easiest way I would do it is by including Name and Charity within the XElements they belong to.
What I would recommend you do is first reformat your document so that it looks like this:
<Funrun>
<Venue>
<Name>Roker Park</Name>
<Runner1>
<charity>Cancer Research</charity>
<Firstname>Roger</Firstname>
<Lastname>Malibu</Lastname>
<Sponsorship>550</Sponsorship>
</Runner1>
<Runner2>
<charity>Arthritis UK</charity>
<Firstname>Adam</Firstname>
<Lastname>White</Lastname>
<Sponsorship>340</Sponsorship>
</Runner2>
</Venue>
</Funrun >
Note that you could get even simpler by combining all the elements under "Funrun" (example: "Venue") and just iterate through all of them without having to switch documents.
Next moving over to C#:
List<string> VenueNames = new List<string>();
var doc = XDocument.Load("XMLFile1.xml");
var doc2 = XDocument.Load("XMLFile2.xml");
var doc3 = XDocument.Load("XMLFile3.xml");
foreach (XElement element in doc.Root.Descendants("Venue"))
{
VenueNames.Add(element.Element("Name").Value.ToString());
}
//Copy paste this code for each document you would like to search through, though of course change "doc" to say, "doc2".
So just real quick, what this code will do is it will first open the Root element in the XDocument. It will find Decendants of that element with the name, "Name", and for each of those it will copy its value as a string into your list.
List<string> xmlFilePaths = new List<string>
{
#"Path\\SomeJson.txt",
#"Path\\SomeJson1.txt"
};
var venues = xmlFilePaths.Select(fp => XDocument.Load(fp).Descendants("Venue")?.FirstOrDefault()?.Attribute("name")?.Value).Distinct().ToList();
I have a c# app that writes to XML using the following code:
//Write last compliant elements to state XML if allCompliant bool == true
if (allCompliant == true)
{
if (File.Exists(MainEntry.thirdPartyStateXMLPath))
{
XDocument doc = XDocument.Load(MainEntry.thirdPartyStateXMLPath);
DateTime localCurrentTime = DateTime.Now;
DateTime utcCurrentTime = DateTime.UtcNow;
XElement root = new XElement("Compliance_Status");
root.Add(new XElement("Last_Known_Compliant_UTC", utcCurrentTime));
root.Add(new XElement("Last_Known_Compliant_LocalTime", localCurrentTime.ToString()));
doc.Element("Compliance_Items").Add(root);
doc.Save(MainEntry.thirdPartyStateXMLPath);
}
}
That renders the following XML:
<?xml version="1.0" encoding="utf-8"?>
<Compliance_Items>
<Compliance_Status>
<Last_Known_Compliant_UTC>2014-04-03T23:22:31.507088Z</Last_Known_Compliant_UTC>
<Last_Known_Compliant_LocalTime>4/3/2014 4:22:31 PM</Last_Known_Compliant_LocalTime>
</Compliance_Status>
</Compliance_Items>
This code generates the *Last_Known_Compliant_UTC* and *Last_Known_Compliant_LocalTime* elements and values. On subsequent runs of the code I want it to only replace the values of the existing elements, but as written now the following is re-created each time and keeps stacking in the XML:
<Compliance_Status>
<Last_Known_Compliant_UTC>2014-04-03T23:22:31.507088Z</Last_Known_Compliant_UTC>
<Last_Known_Compliant_LocalTime>4/3/2014 4:22:31 PM</Last_Known_Compliant_LocalTime>
</Compliance_Status>
How can I achieve the desired effect?
If you want to get a specific item and modify it you can do the following:
var xmlDocument = XDocument.Load("path");
var element = xmlDocument
.Descendants("Compliance_Status")
.FirstOrDefault(x => (DateTime)x.Element("Last_Known_Compliant_UTC") == someValue)
if(element != null)
/* update the value simply using element.Value = something
and save the xml file xmlDocument.Save("path") */
If you want to replace your element with another element you can use XElement.ReplaceWith method.
I have an string parameter with xml content in it. Basically the string have an XML inside.
string S = funcThatReturnsXML (parameters);
S have the next text:
<?xml version="1.0" encoding="utf-8" ?>
<tagA>
<tagB>
<tagBB>
..
.
.
</tagBB>
.
.
</tagB>
<tagC>
..
..
.
</tagC>
</tagA>
The funcThatReturnsXML (parameters) creates an XmlDocument object but the return it as a string, I cant change this function, to much stuff works with it.
Tried to create XmlDocument objetc but the SelectSingleNode return null.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(S);
XmlNode root = xmlDoc.SelectSingleNode("tagB");
How can I delete from string S (not XML Object) specific node, for example <tagB>
EDIT: this is the XML I tested with:
<?xml version="1.0" ?>
- <Request xmlns:xsi="http://www.mysite.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <info xmlns="http://www.mysite.com">
<RequestTR>54</RequestTR>
<time>2013-12-22</time>
</info>
- <Parameters xmlns="http://www.mysite.com">
<id>3</id>
<name>2</name>
</Parameters>
<title>Request</title>
</Request>
Try this:
string S = funcThatReturnsXML(parameters);
var doc = XDocument.Parse(S);
var nodeToRemove = doc.Descendants("tagB");
nodeToRemove.Remove();
That will remove all nodes named "tagB" from string S which contains xml.
UPDATE 1:
Sorry, i missed to include one more line:
S = doc.ToString();
My first code above removed "tagB" from doc but didnt save it back to S variable.
UPDATE 2:
I tested with following xml which contain attribute:
<tagA attribute="value">
<tagB>
<tagBB>
</tagBB>
</tagB>
<tagC></tagC>
</tagA>
and the output of Console.WriteLine(S):
<tagA attribute="value">
<tagC></tagC>
</tagA>
UPDATE 3:
Given your updated xml format, I know why my previous code didn't work for you. That was because your xml have namespace (xmlns) declared. The solution is to use LocalName when searching for the node to be removed, that will search for node name while ignoring its namespace. The follwoing example shows how to remove all "info" node:
var doc = XDocument.Parse(S);
var nodeToRemove = doc.Descendants().Where(o => o.Name.LocalName == "info");
nodeToRemove.Remove();
S = doc.ToString();
If you can determine the particular outer element to remove from the returned XML, you could use LINQ to XML:
var returnedXml = funcThatReturnsXML(parameters);
var xmlElementToRemove = funcThatReturnsOuterElement(returnedXml);
var xelement = XElement.Load("XmlDoc.txt");
xelement.Elements().Where(e => e.Name == xmlElementToRemove).Remove();
For example:
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main(string[] args)
{
// pretend this is the funThatReturnsXML return value
var returnedXml = "<tagB><tagBB></tagBB></tagB>";
// get the outer XML element name
var xmlElementToRemove = GetOuterXmlElement(returnedXml);
// load XML from where ever
var xelement = XElement.Load("XmlDoc.txt");
// remove the outer element and all subsequent elements
xelement.Elements().Where(e => e.Name == xmlElementToRemove).Remove();
}
static string GetOuterXmlElement(string xml)
{
var index = xml.IndexOf('>');
return xml.Substring(1, index - 1);
}
}
Note that the above is a "greedy" removal method, if there is more than once element with the name returned via the GetOuterXmlElemet method they will all be removed. If you want a specific instance to be removed then you will require something more sophisticated.
Building on your edit:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(S);
var nodeA = xmlDoc.SelectSingleNode("/tagA");
var nodeB = nodeA.SelectSingleNode("tagB");
nodeA.RemoveChild(nodeB);
To remove (possibly) multiple tagB nodes in unknown positions, you may try:
var bees = xmlDoc.SelectNodes("//tagB");
foreach (XmlNode bee in bees) {
var parent = bee.ParentNode;
parent.RemoveChild(bee);
}
I'm trying to insert an element at a specific point within my file, then save that file out. However, I can't seem to get it right. My XML layout is like this:
<?xml version="1.0" encoding="utf-8"?>
<Settings>
<Items />
<Users />
</Settings>
This is my current code:
XDocument xd = XDocument.Load(#"C:\test.xml");
var newPosition = xdoc.Root.Elements("Users");
//I've tried messing around with newPosition methods
XElement newItem = new XElement("User",
new XAttribute("Name", "Test Name"),
new XAttribute("Age", "34"),
);
//how can I insert 'newItem' into the "Users" element tag in the XML file?
xd.Save(new StreamWriter(#"C:\test.xml"));
I'd like to use Linq to XML to insert 'newItem' into the tag. Thanks for any help on this.
Just find the Users element, and append it:
// Note that it's singular - you only want to find one
XElement newPosition = xdoc.Root.Element("User");
XElement newItem = new XElement("User",
new XAttribute("Name", "Test Name"),
new XAttribute("Age", "34"));
// Add the new item to the collection of children
newPosition.Add(newItem);
Your use of var here was leading you astray - because the type of newPosition in your code was really IEnumerable<XElement>... you were finding all the User elements. (Okay, there would only have actually been one element, but that's irrelevant... it was still conceptually a sequence.)