How to update an empty node using Xpath navigator - c#

i have an XML like this
<main>
<reportPath>d:\reports</reportPath>
<errorPath>D:\Error</errorPath>
<project>D:\xyz.txt</project>
<value />
</main>
here "value" is an empty node. using Xpath navigator, I am able to reach Value node, but not able update it.
using something like :
XPathNavigator currentnavigator = navigator.SelectSingleNode("//*/value");
Can anyone give me some idea how to edit this node i.e. add value to it which can be a string path.
will get appended at the end ?

If your navigator is editable, you can just use SetValue():
currentnavigator.SetValue("somePath");
That being said, I would recommend you to use LINQ to XML instead, I find it much easier to use:
XDocument doc = …;
doc.Root.Element("value").Value = "somePath";

Related

Select a XML node based on a sibling node

I'm trying to select an XML node, where another child of the parent node contains a specific value.
The XML looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<AuthorIT>
<Objects>
<Media>don't care</Media>
<Style>don't care</Style>
<Book>don't care</Book>
<Topic>don't care</Topic>
<Topic>
<Object>
<Description>Performance Evidence</Description>
</Object>
<Text>This is what I want to select</Text>
</Topic>
</Objects>
</AuthorIT>
I'm using XPath in C#. My query at the moment looks like this: (but doesn't work, obviously)
docNav = new XPathDocument(localFile);
nav = docNav.CreateNavigator();
xPath = "//Topic[Object/Description = 'Performance Evidence']/Text";
string value = nav.SelectSingleNode(xPath).Value;
How do I get the contents of the Text node, from the Topic that has an Object/Description value of "Performance Evidence"?
You should first select the Description node containing your needle text, then move back to the common parent and select the Text nodes that are its children.
//Topic/Object/Description[text()='Performance Evidence']/../../Text/text()
As Kirill Polishchuk said in a comment, my XPath was correct.
What I left out of the example XML was the key to the solution... Namespace!
I found my answer on this other question: Using Xpath With Default Namespace in C#

SelectSingleNode in XML for select second element doesn't work in C#

I have problem to select second node from root element in following example xml code:
<?xml version="1.0"?>
<config>
<FirstNode>
<ShowBlahBlah>
</ShowBlahBlah>
</FirstNode>
<SecondNode>
<ShowBlahBlah>
</ShowBlahBlah>
</SecondNode>
</config>
and using this C# code to select SecondNode:
XmlDocument doc = new XmlDocument();
doc.LoadXml(sReadXML);
XmlNode sChangesLog = doc.SelectSingleNode("config").SelectSingleNode("//SecondNode").SelectSingleNode("//ShowBlahBlah")
XmlNodeList sChildNodes = sChangesLog.ChildNodes;
but it selecting first node and return its value!
how can I fix this problem?
You're using // at the start of each of your selections - which means "find descendant nodes starting at the root" (so the context is irrelevant). You could either do things in one step as per Jeffrey's answer, or use relative paths:
doc.SelectSingleNode("config")
.SelectSingleNode("SecondNode")
.SelectSingleNode("ShowBlahBlah")
Personally I'd use LINQ to XML instead, if at all possible:
var doc = XDocument.Parse(sReadXml);
var changes = doc.Root.Element("SecondNode").Element("ShowBlahBlah");
LINQ to XML is generally a much cleaner API than XmlDocument et al.

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;

Get specific data from XML document

I have xml document like this:
<level1>
<level2>
<level3>
<attribute1>...</attribute1>
<attribute2>false</attribute2>
<attribute3>...</attribute3>
</level3>
<level3>
<attribute1>...</attribute1>
<attribute2>true</attribute2>
<attribute3>...</attribute3>
</level3>
</level2>
<level2>
<level3>
<attribute1>...</attribute1>
<attribute2>false</attribute2>
...
...
...
I'm using c#, and I want to go thru all "level3", and for every "level3", i want to read attribute2, and if it says "true", i want to print the corresponding attribute3 (can be "level3" without these attributes).
I keep the xml in XmlDocument.
Then I keep all the "level3" nodes like this:
XmlNodeList xnList = document.SelectNodes(String.Format("/level1/level2/level3"));
(document is the XmlDocument).
But from now on, I don't know exactly how to continue. I tried going thru xnList with for..each, but nothing works fine for me..
How can I do it?
Thanks a lot
Well I'd use LINQ to XML:
var results = from level3 in doc.Descendants("level3")
where (bool) level3.Element("attribute2")
select level3.Element("attribute3").Value;
foreach (string result in results)
{
Console.WriteLine(result);
}
LINQ to XML makes all kinds of things much simpler than the XmlDocument API. Of course, the downside is that it requires .NET 3.5...
(By the way, naming elements attributeN is a bit confusing... one would expect attribute to refer to an actual XML attribute...)
You can use LINQ to XML and reading this is a good start.
You can use an XPath query. This will give you a XmlNodeList that contains all <attribute3> elements that match your requirement:
var list = document.SelectNodes("//level3[attribute2 = 'true']/attribute3");
foreach(XmlNode node in list)
{
Console.WriteLine(node.InnerText);
}
You can split the above xpath query in three parts:
"//level3" queries for all descendant elements named <level3>.
"[attribute2 = 'true']" filters the result from (1) and only keeps the elements where the child element <attribute2> contains the text true.
"/attribute3" takes the <attribute3> childnode of each element in the result of (2).

How to get the immediate child elements of the root element using C# and XML?

<Document>
<Heading1>
<text>Heading Title</text>
<para>para1</para>
<para>para2</para>
<para>para3</para>
</Heading1>
<Heading1>
<text>2nd Heading Title</text>
<para>para4</para>
<para>para5</para>
<para>para6</para>
<Heading2>
<text>3rd Heading Title</text>
<para>para4</para>
<para>para5</para>
</Heading2>
</Heading1>
</Document>
This is XML Document. Now, i want to parse this XML file using C# (4.0). Here, I want to get all the Heading1 elements without using that element name in my program. For example, don't use document.GetElementsByTagName("Heading1");. How i get it. Guide me get out of this issue.
Thanks & Regards.
Using LINQ to XML, you can do:
var headings = yourXDocument.Root.Elements();
Using Nodes() instead of Elements() will also return text nodes and comments, which is apparently not what you want.
You can access the child elements of the document or element through the Elements() method if using LINQ to XML.
XDocument doc = ...;
var query = doc.Root.Elements();
If you're using XmlDocument, this works:
var elements = doc.SelectNodes("/*/*");
That finds all child elements of the top-level element irrespective of any of their names. It's usually safer to specify the names if you know them, so that elements with unexpected names don't get returned in your list - use /Document/Heading1 to do this.

Categories

Resources