Recreating XML but passing variable into the data - c#

I am trying to Create an XML with the below format but keep having issues. I am new to both c# and XML and hit a brick wall on this one. The reference XML i have is this
<workspace name="Remote Apps" xmlns="http://schemas.microsoft.com/ts/2008/09/tswcx" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<defaultFeed url="CHANGEME" />
</workspace>
I need to be able to recreate this file with the adjustment of the url Value. I have tried loading this XML on its own and the alter the value and also tried to recreate from scratch. Both i have hit a blank wall.
Last attempt to do this was
XDocument doc = XDocument.Load("cloud.xml");
var element = doc.Elements("defaultFeed")
.Single(x => x.Attribute("url").Value == "ChangeMe");
element.SetAttributeValue("url", fullurl);
doc.Save(CloudFileLocation);
If someone would be kind enough to help me out with this either writing from scratch or altering the code from a local file i would appreciate it. (Create from scratch would be preferred)

There are three probems with your code:
doc.Elements("defaultFeed") searches for an element named defaultFeed as child of the document. Your element is however a child of the root node workspace.
Solution: change to
doc.Root.Elements("defaultFeed")
This attribute xmlns="http://schemas.microsoft.com/ts/2008/09/tswcx" says that all elements where the namespace is not explicitely specified, are in the namespace http://schemas.microsoft.com/ts/2008/09/tswcx. Elements("defaultFeed") however searches for elements without any namespace.
Solution: change to
XNamespace tswcx = "http://schemas.microsoft.com/ts/2008/09/tswcx";
doc.Root.Elements(tswcx + "defaultFeed")
The third one is a simple typo: You should compare to "CHANGEME", not to "ChangeMe"

Related

How to insert the new element on XMLNode in C#

I am trying to insert a new element into the XmlNode in C# code,
How to insert the <delimiter>##<delimiter> element in inside the "/TestBooks/template/field" root. (Screenshot1)
enter image description here
Inside the <field> element, i need to insert the <delimiter> element, based on id element <Id>11-09-2020-505</Id>. (Screenshot2)
enter image description here
First of all you really shouldn't use pictures in questions -- we are taking the time to type you an answer you can take the time to use copy and paste and format your questions.
I'd like to answer your questions but I'm concerned about the questions because it implies that you are adding in markers to aid in the parsing of the data. You really shouldn't need to parse XML.
There are many great parsers of XML including one built into C# you should not roll your own.
In the XML standard the order of the children not defined. If you put a child as the "first" child, there is no reason to expect that a parser would list it as first.
(To have order in children you should just add an order attribute)
Because of these reason it should not matter where in the list of children you add the child.
So we can tell you how to add a child but we can't "put it in a specific spot" since children don't have an order.
In summary, it is not possible to do what you ask.

Replace Self Closing Node with Paired Empty nodes in XML in SQL Server

I am writing an SSIS Package where we bring in an existing XML and then Add couple nodes to it and then spit it back out. It has to be exactly the same way it goes in and comes back out, except for the 3 new columns. I use a combination of SQL Server and C# Script in SSIS to do this.
However this is the issue:
The original XML document has these nodes for example:
<Base_Entry>
<Customer></Customer>
<Profit></Profit>
...
When I put the data into the database in SQL Server and then do some parsing for the other nodes and then do try to output the XML back out it comes out looking like this for the 2 nodes.
<Base_Entry>
<Customer />
<Profit />
Now I know that semantically the self closing node is the same as the one on top. It's for blanks. However, our vendor can't work with it and is requesting it to NOT be a self closing node. He wants it just like the original.
However I can't figure it out no matter what I do in SQL Server. Blank nodes come out with a self closing node.
I tried changing it in C# using a script task for SSIS trying to do a
XMLOutput.InnerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
Dts.Variables["XMLOutput"].Value.ToString().Replace("<Customer />", "<Customer></Customer>");
The XMLOutput.InnerXml has the entire XML content and I am trying to just replace the words in there manually by trying to do a Replace.
If anyone can help me out how to do it with just SQL Server first, that would be appreciated the most. IF not, is there a way to just replace it in C#?

Overwrite specific XML node

I have a XML file of the following format:
<Alarms>
<Alarm>
<Id>1</Id>
<Severity>Warning</Severity>
<Comments></Comments>
</Alarm>
<Alarm>
<Id>2</Id>
<Severity>Error</Severity>
<Comments>Restart the machine</Comments>
</Alarm>
...
My program has a GUI which gives the user the ability to edit the Comments of an alarm. I am trying to come up with the best solution for the actions to take when a user is done editing and wants to save the changes. The XML file isn't extremely large (it does not warrant a database) but large enough that I do not want to overwrite the entire thing every time a change is made to a single alarm. Is it possible to target only a specific node and edit the Comments attribute without then having to re-write everything?
I'm looking for a XML-specific solution... I want to avoid regular flat-file methods that involve going to a specific line in a file and then editing that line. Perhaps something exists for XML files that I'm not privy to. I'm currently working with a .NET 2 project but will soon be upgrading to 4.5, so any solution works for me.
You can load up the xml in XmlDocument class. Navigate with an XPath query to the Comments node you want to edit and change the value. When you are done, just save the document to the same file name or a different one.
Here is an example using a Console Application.
// The Id of the Alarm to edit
int idToEdit = 2;
// The new comment for the Alarm
string newCommentValue = "Here is a new comment";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode commentsElement = doc.SelectSingleNode(String.Format("Alarms/Alarm[Id = '{0}']/Comments", idToEdit));
commentsElement.InnerText = newCommentValue;
doc.Save(Console.Out);
Here is a working fiddle: https://dotnetfiddle.net/eQROet

Adding an attribute to xml document child node using linq

I'm trying to create an element and defining the path to the xml document, one of my tries was:
XElement main = XElement.Load(xmlpath);
Then i tried to select the existing element that I want to add an attribute
main.XPathSelectElement("/Row/ip_addresses").SetAttributeValue("id", sp_range.ToString());
Las tried these both
main.XPathSelectElement("/Row/ip_addresses").ReplaceAttributes("id", sp_range.ToString());
There is no errors presented in this code just nothing happens to the xml document and the existing Element, the existing child element is and the Parent is I am using Xpath to navigate to the child element that I want to add attribute to that don't exist according to Linq we are supposed to be able to change attributes that exist or don't exist and change ElementTags that exist or create Elements that don't exist.
Please any advise would help
You don't appear to be persisting/saving the changes...
Try the XElement.Save method
You are selecting from "Row" which doesn't exist under the current element. Current element itself is the "Row". As such, you need to select from the root "/ip_addresses", not from "/Row/ip_addresses".
main.XPathSelectElement("/ip_addresses").SetAttributeValue("id",sp_range.ToString()));

Copy an existing XML element into the same document

I am building up an XML document using c#. I use AppendChild to add an element called say "test" to a parent element in the document.
I then build up more of the xmlDocument but further down the same document I wish to append the same element "test" to a different node.
I have tried using AppendChild but it added it to the new node and removed it from the existing one. Which I guess is expected. I was just wondering is there anything available that I can use to copy the existing element and add it to a new node without removing it from the existing position?
To perhaps help explain the following code results in the test element only appearing in parentElement2.
parentElement1.AppendChild(test)
...
parentElement2.AppendChild(test)
Is there anyway I can insert test into both parent elements?
Hope this makes sense.
This should be possible with the CloneNode method. It lets you create a (possibly deep) copy of a node, which you can then insert wherever you like in your document.

Categories