473,322 Members | 1,562 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Parsing XML nodes by Attribute

I have this simple xml file which wont ever get beyong 3 nodes deep. I need
to get the value of the child node of any node with an id of '63'. So fir
instance I would be returned 'False' from the example below.

Ive attached an XML snippet and a cC# code snippet. The piece of code is not
working as I am not too familiour with parsing XML files.I think I need to
load the attributes into an array and loop through them to check for that
value. Could anyone help me with this? Is there an wasier way?

Thanks,
Grant

-------Sample XML-----------------

<session-data>
<attr-inst id="p1" state="known">
<val>Wilma Flintstone</val>
</attr-inst>
<attr-inst id="63" state="known">
<val>false</val>
</attr-inst>
</session-data>

----------Sample C# Code------------

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
XmlNodeList nodeList = xmlDoc.SelectNodes("//session-data/attr-inst");
foreach (XmlNode node in nodeList)
{
if ( node.Attributes["id"].Attributes == "63")
{
node.Attributes["id"].FirstChild.Value = newDate;
}
}
Nov 12 '05 #1
6 1702


Grant wrote:
I have this simple xml file which wont ever get beyong 3 nodes deep. I need
to get the value of the child node of any node with an id of '63'. So fir
instance I would be returned 'False' from the example below.


If you only want to read out values then XPathDocument is one way to do
it, it is easy to write one XPath expression selecting the nodes as
described above:

XPathDocument xpathDocument = new XPathDocument(@"test2005031602.xml");
XPathNavigator xpathNavigator = xpathDocument.CreateNavigator();
XPathNodeIterator nodeIterator =
xpathNavigator.Select(@"/session-data/attr-inst[@id = '63']/*");
while (nodeIterator.MoveNext()) {
Console.WriteLine("Found value \"{0}\".",
nodeIterator.Current.Value);
}

--

Martin Honnen
http://JavaScript.FAQTs.com/
Nov 12 '05 #2
I managed to find a way of going directly to that specific node using the
code below. What I need to do now is modify the child node value that it
picks up. Problem is it is wiping out the '<val>' and '</val>'part of the
node. So when I run the code from the code snippet section below, against
the Original XML snippet, I get the modified XML output. You can see it has
deleted the child node and simply added the new value as a value of its
parent node.

how do I simply change the value of that node Ive found?
Thanks,
Grant
------Original XML-----------
<attr-inst id="63" state="known">
<val>false</val>
</attr-inst>

------modified XML-----------
<attr-inst id="63" state="known">true</attr-inst>

--------Code Snippet------------
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
XmlNodeList nodeList = xmlDoc.SelectNodes("//session-data/attr-inst");
XmlNode findnode;
XmlElement root = xmlDoc.DocumentElement;
findnode = root.SelectSingleNode("descendant::attr-inst[@id='63']");
findnode.InnerXml = "true";
xmlDoc.Save(fileName);

"Martin Honnen" <ma*******@yahoo.de> wrote in message
news:ei**************@TK2MSFTNGP14.phx.gbl...


Grant wrote:
I have this simple xml file which wont ever get beyong 3 nodes deep. I
need to get the value of the child node of any node with an id of '63'.
So fir instance I would be returned 'False' from the example below.


If you only want to read out values then XPathDocument is one way to do
it, it is easy to write one XPath expression selecting the nodes as
described above:

XPathDocument xpathDocument = new
XPathDocument(@"test2005031602.xml");
XPathNavigator xpathNavigator = xpathDocument.CreateNavigator();
XPathNodeIterator nodeIterator =
xpathNavigator.Select(@"/session-data/attr-inst[@id = '63']/*");
while (nodeIterator.MoveNext()) {
Console.WriteLine("Found value \"{0}\".",
nodeIterator.Current.Value);
}

--

Martin Honnen
http://JavaScript.FAQTs.com/

Nov 12 '05 #3


Grant wrote:
I managed to find a way of going directly to that specific node using the
code below. What I need to do now is modify the child node value that it
picks up. Problem is it is wiping out the '<val>' and '</val>'part of the
node. So when I run the code from the code snippet section below, against
the Original XML snippet, I get the modified XML output. You can see it has
deleted the child node and simply added the new value as a value of its
parent node.


You do not access the right node, as suggested use the XPath expression
@"/session-data/attr-inst[@id = '63']/*"
then you have the element child nodes you are looking for, perhaps if
you know the element name of the child node you want
@"/session-data/attr-inst[@id = '63']/val"
then you can use SelectSingleNode and change
node.InnerText = "true";
Or access the text node itself e.g.
@"/session-data/attr-inst[@id = '63']/val/text()"
then use
node.Value = "true";

--

Martin Honnen
http://JavaScript.FAQTs.com/
Nov 12 '05 #4
That works great - So its simply standard Xpath expressions that can be used
to browse nodes, exactly the same as XSLT.

Thanks for your help,
Grant

"Martin Honnen" <ma*******@yahoo.de> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...


Grant wrote:
I managed to find a way of going directly to that specific node using the
code below. What I need to do now is modify the child node value that it
picks up. Problem is it is wiping out the '<val>' and '</val>'part of the
node. So when I run the code from the code snippet section below, against
the Original XML snippet, I get the modified XML output. You can see it
has deleted the child node and simply added the new value as a value of
its parent node.


You do not access the right node, as suggested use the XPath expression
@"/session-data/attr-inst[@id = '63']/*"
then you have the element child nodes you are looking for, perhaps if you
know the element name of the child node you want
@"/session-data/attr-inst[@id = '63']/val"
then you can use SelectSingleNode and change
node.InnerText = "true";
Or access the text node itself e.g.
@"/session-data/attr-inst[@id = '63']/val/text()"
then use
node.Value = "true";

--

Martin Honnen
http://JavaScript.FAQTs.com/

Nov 12 '05 #5
Your findnode has a child node below it <val> so you should be
modifying the value of that.
Try replacing
findnode.InnerXml = "True";
with
XmlElement val_node = (XmlElement)findnode.FirstChild;
val_node.NodeValue = "True;

Nov 12 '05 #6
Is that the same as what I have currently? One last question on this: How do
I modify the Node ID?? So in the example XML I need id='63' to become
id='999' or whatever. In my problematic code section I removed the "/val");"
section because I dont want it looking at the child node - but when it
doesnt change the attribute id value for some reason - it tells me "the
expression passed to this method must result in a nodeset"

What am I doing wrong?
Thanks.
----------Problematic Code: setting Attribute ID------------
findnode = root.SelectSingleNode(@"/session-data/attr-inst/[@id = '" +
FactIDToReplace + "']");
if ( findnode != null )
{
findnode.Attributes["ID"].InnerText = newValue;
}

----------XML------------
<attr-inst id="63" state="known">
<val>false</val>
</attr-inst>

----------Working Code------------
findnode = root.SelectSingleNode(@"/session-data/attr-inst[@id = '" +
FactIDToReplace + "']/val");
if ( findnode != null )
{
findnode.InnerText = newValue;
}

<ge*****************@yahoo.co.uk> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Your findnode has a child node below it <val> so you should be
modifying the value of that.
Try replacing
findnode.InnerXml = "True";
with
XmlElement val_node = (XmlElement)findnode.FirstChild;
val_node.NodeValue = "True;

Nov 12 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: Luis P. Mendes | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I only know a little bit of xml and I'm trying to parse a xml document in order to save its elements in a file (dictionaries inside a list)....
2
by: AR | last post by:
Hi, I have an xml like this: <a> a 1 <b font-size="10">b 2</b> x <c font-size="14" font-weight="bold">c 3</c> y </a>
4
by: Erik Moore | last post by:
I am both producing and parsing an xml document that needs to be validated against a schema. I wanted some consumers of the document to have the option of not performing a validation, so I left the...
2
by: Greg | last post by:
Hi. I have a rather large xml document (object) that can have one or more nodes with a certain attribute throughout (at ANY depth, not at the same level necessarily). I need to find this...
5
by: Grant | last post by:
I have this simple xml file which wont ever get beyong 3 nodes deep. I need to get the value of the child node of any node with an id of '63'. So fir instance I would be returned 'False' from the...
8
by: Fabio Cannizzo | last post by:
I have an XML file based on an XSD schema. It represents the content of a treeview (or a menu system), where the nodes are always of the same few types, but can be arbitrarily nested. I am...
4
by: Mike [MCP VB] | last post by:
Hi, I hope this is the right place to ask. I have an xml file thus: <?xml version="1.0" encoding="UTF-8"?> <Message xmlns="urn:myurl-org:ns2"...
5
by: WTH | last post by:
In C++ I had, long ago, written my own XML parsing class as I never found even a half decent node based hierarchical solution that was simple, now that I'm starting to develop tools in C# (as a...
0
by: gnewsgroup | last post by:
I need to bind *some* nodes of an xml document to an asp.net Menu control. The problem is that the XML document uses the same node name and attribute name for for the entire document among all...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.