Replace XML attributes - c#

I have an XML file, that contain IDs in an attribute called translatedID.
This attribute exists in almost every element in the doc, so instead of searching for each element one by one, I want to select all the translatedID in the document and run some code on each attribute's value.
The needed result is - replacing the translatedID with some other data.
How can I select ALL the translatedID that exists in my XML document?

Sounds like a great case for LINQ to XML:
XDocument doc = XDocument.Load("doc.xml");
var attributes = doc.Descendants().Attributes("translatedID");
foreach (var attribute in attributes)
{
attribute.Value = DoSomethingWith(attribute.Value);
}
doc.Save("transformed.xml");
(That's assuming you want to change the value of the attribute. If you want to do something else, that's doable - but you'll need to give more information.)

Related

Create tag in XML with C#

I have a very frustrating issue which I'm hoping will actually be something extremely simple. Apologies in advance if my terminology in XML files is wrong.
Basically I have a fairly simple XML file, here is an extract of one node:
<Attr num="108" name="Title" desc="The title of this file." type="s" ord="1" value="Test Title">
I can read and write the value key of the node fairly easily, but only if the value key exists.
I can use this code to write values back to the file:
XmlNode node = xmlDoc.SelectSingleNode("//ma:Attr[#name='Title']/#value", ns);
node.Value = partname.Text;
xmlDoc.Save(sympath);
However, if the XML file has the node of the correct name, but does not have a value key then it fails. For example, in some files the XML looks like this:
<Attr num="108" name="Title" desc="The title of this file." type="s" ord="1">
So I'm going round and round in circles just trying to add value="something" to that node if it doesn't already exist. Is there a way to do this? I can add child elements, but I just want to add the value in that string!
I have tried searching for an answer, but all the other similar issues seem to be about adding or modifying child elements.
Thank you,
Andrew
Actually, XmlElement.SetAttribute() alone did the job :
var node = (XmlElement)xmlDoc.SelectSingleNode("//ma:Attr[#name='Title']", ns);
node.SetAttribute("value", partname.Text);
Select parent element instead of the attribute, check if value attribute exists in that element and take action accordingly i.e add attribute or just update the value :
var node = (XmlElement)xmlDoc.SelectSingleNode("//ma:Attr[#name='Title']", ns);
var attr = node.Attributes["value"];
if(attr != null)
{
attr.Value = partname.Text;
}
else
{
node.SetAttribute("value", partname.Text);
}

Retrieve Values manually from XML InnerXML

I have been trying to deserialize the InnerXML into a class and for some reason the XML keeps changing shape and however many times I try to get the class right it seems to change shape again.
So I have given up and decided to try another method.
Is it possible to retrieve the value of a parameter within the InnerXML manually using c#?
Say for example, my XML innerXML looked like this:
<Timestamp>2014-08-22T21:45:00Z</Timestamp>
<Subscriber>https://www.dogdoza.co.uk</Subscriber>
<Order>
<OrderID>111867</OrderID>
<InvoiceNumber>DOZA-9725410</InvoiceNumber>
<CustomerID>4542</CustomerID>
Is it possible to pull out say the value of Subscriber
If this is possible I can just pull out the values I want manually. Not ideal, but there are only about 10...
I have looked around but not managed to find any code I can get working..
Can anyone please give me any guidance?
Thanks
You can do achieve what you want using LINQ to XML:
XElement myXml = XElement.Load(#"XmlLocationHere");
XElement subscriber = myXml.Descendants("Subscriber").FirstOrDefault();
XElement.Descendants returns a collection of the descendant elements for this document or element, in document order. This method will return an IEnumerable<XElement>, since there might be more than one "Subscriber" element, but in your case, we choose FirstOrDefault, which returns the first occurrence.
Try loading your XML into an XDocument. Then try to use XPathSelectElement to find the specific value you want.
It could be that you need to wrap your inner xml into a root element, because it doesn't accept multiple roots.
Pseudo example:
// set up your xml document
string xml = "<rootelement>" + myInnerXml + "</rootelement>";
XDocument doc = new XDocument();
doc.Parse(xml);
XElement subscriber = doc.XPathSelectElement("/rootelement/Subscriber");
string value = subscriber.Value;

XML to Linq getting child nodes with attribute value

Variations of this question have already been asked but I have not found one that can help me with the problem i am having.
Given and XML file of this format:
<TopLevel>
<SecondLevel Name="Name" Color="Blue">
<ChildNode1></ChildNode1>
<ChildNode2></ChildNode2>
</SecondLevel>
<SecondLevel Name="Name2" Color="Red">
...
</SecondLevel>
</topLevel>
I have the value to the attribute Color.
What I would like is to be able to first find the Name corresponding to that color, and then find all the childnodes.
I prefer to use Xelement over XDocument.
This is what I have attempted so far, but with no luck.
XElement xelement = XElement.Load("XmlFile.xml");
IEnumerable<XElement> Name2=
from el in xelement.Elements("SecondLevel")
where el.Attribute("Color") == "Red"
select el;
With the result of that, I will eventually want to format it into a datatable. Is this doable?
You just missing cast of attribute to string (or getting it's value directly - see notes at the end). Also you can select Name attribute value to have sequence of strings instead of XElements:
XElement xelement = XElement.Load("XmlFile.xml");
IEnumerable<string> names =
from el in xelement.Elements("SecondLevel")
where (string)el.Attribute("Color") == "Red" // here
select (string)el.Attribute("Name");
NOTE: You can also access attribute value directly with el.Attribute("Color").Value but that will throw exception if element don't have Color attribute. So casting is more safe, but accessing value can be option if you want your code to fail fast if xml is not valid.
BTW you can also use XPath to get second level elements which have required color:
IEnumerable<XElement> secondLevels =
xelement.XPathSelectElements("SecondLevel[#Color='Red']");

Checking if value exists in name attribute

<root>
<data name="ID1"></data>
<data name="ID2"></data>
</root>
XDocument xmlDoc = XDocument.Load(xmlFile);
bool exists = (from elem in xmlDoc.Descendants("root")
where elem.Element("data").Attribute("name").Value == "ID1"
select elem).Any();
It doesn't see that ID1 already exists. What am I doing wrong?
Based on what you've shown, first I have to point out that the XML snippet is not valid XML. The data nodes are not closed.
Assuming this is a valid XML document, it would ultimately depend on what the type is for your variable XMLDoc.
If it was an XDocument, then that code snippet should work and the value of exists would be true. The document contains a descendant called root and it could go about its business.
If it was an XElement on the other hand, then that code snippet should fail and the value of exists would be false. The XMLDoc variable would be referring to the root element already and there clearly isn't any descendants called root.
You should rewrite your query however, maybe something more like this:
// please follow .NET naming conventions and use lowercase for local variables
XDocument xmlDoc = XDocument.Load(xmlFile);
// iterate over the `data` elements, not the `root` elements
bool exists = (from data in xmlDoc.Element("root").Elements("data")
where (string)data.Attribute("name") == "ID1"
select data).Any();
// using the cast is a personal style choice
// using `XAttribute.Value` is fine too in this case

Setting attributes in an XML document

I'm writing one of my first C# programs. Here's what I'm trying to do:
Open an XML document
Navigate to a part of the XML tree and select all child elements of type <myType>
For each <myType> element, change an attribute (so <myType id="oldValue"> would become <myType id="newValue">
Write this modified XML document to a file.
I found the XmlDocument.SelectNodes method, which takes an XPath expression as its argument. However, it returns an XmlNodeList. I read a little bit about the difference between an XML node and an XML element, and this seems to explain why there is no XmlNode.SetAttribute method. But is there a way I can use my XPath expression to retrieve a list of XmlElement objects, so that I can loop through this list and set the id attributes for each?
(If there's some other easier way, please do let me know.)
Simply - it doesn't know if you are reading an element or attribute. Quite possibly, all you need is a cast here:
foreach(XmlElement el in doc.SelectNodes(...)) {
el.SetAttribute(...);
}
The SelectNodes returns an XmlNodeList, but the above treats each as an XmlElement.
I am a big fan of System.Xml.Linq.XDocument and the features it provides.
XDocument xDoc = XDocument.Load("FILENAME.xml");
// assuming you types is the parent and mytype is a bunch of nodes underneath
IEnumerable<XElement> elements = xdoc.Element("types").Elements("myType");
foreach (XElement type in elements)
{
// option 1
type.Attribute("id").Value = NEWVALUE;
// option 2
type.SetAttributeValue("id", NEWVALUE);
}
Option 1 or 2 works but I prefer 2 because if the attribute doesn't exist this'll create it.
I'm sitting at my Mac so no .NET for me...
However, I think that you can cast an XmlNode to an XmlElement via an explicit cast.
You should be able to cast the XmlElement to an XmlNode then and get it's children Nodes using something like XmlNode.ChildNodes.

Categories

Resources