473,769 Members | 2,643 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(fil eName);
XmlNodeList nodeList = xmlDoc.SelectNo des("//session-data/attr-inst");
foreach (XmlNode node in nodeList)
{
if ( node.Attributes["id"].Attributes == "63")
{
node.Attributes["id"].FirstChild.Val ue = newDate;
}
}
Nov 12 '05 #1
6 1727


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.C reateNavigator( );
XPathNodeIterat or nodeIterator =
xpathNavigator. Select(@"/session-data/attr-inst[@id = '63']/*");
while (nodeIterator.M oveNext()) {
Console.WriteLi ne("Found value \"{0}\".",
nodeIterator.Cu rrent.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">t rue</attr-inst>

--------Code Snippet------------
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fil eName);
XmlNodeList nodeList = xmlDoc.SelectNo des("//session-data/attr-inst");
XmlNode findnode;
XmlElement root = xmlDoc.Document Element;
findnode = root.SelectSing leNode("descend ant::attr-inst[@id='63']");
findnode.InnerX ml = "true";
xmlDoc.Save(fil eName);

"Martin Honnen" <ma*******@yaho o.de> wrote in message
news:ei******** ******@TK2MSFTN GP14.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.C reateNavigator( );
XPathNodeIterat or nodeIterator =
xpathNavigator. Select(@"/session-data/attr-inst[@id = '63']/*");
while (nodeIterator.M oveNext()) {
Console.WriteLi ne("Found value \"{0}\".",
nodeIterator.Cu rrent.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 SelectSingleNod e 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*******@yaho o.de> wrote in message
news:%2******** ********@TK2MSF TNGP14.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 SelectSingleNod e 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.InnerX ml = "True";
with
XmlElement val_node = (XmlElement)fin dnode.FirstChil d;
val_node.NodeVa lue = "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.SelectSing leNode(@"/session-data/attr-inst/[@id = '" +
FactIDToReplace + "']");
if ( findnode != null )
{
findnode.Attrib utes["ID"].InnerText = newValue;
}

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

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

<ge************ *****@yahoo.co. uk> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Your findnode has a child node below it <val> so you should be
modifying the value of that.
Try replacing
findnode.InnerX ml = "True";
with
XmlElement val_node = (XmlElement)fin dnode.FirstChil d;
val_node.NodeVa lue = "True;

Nov 12 '05 #7

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

Similar topics

16
5996
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). When I access a url from python 2.3.3 running in Linux with the following lines:
2
1568
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
2461
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 nodes in the instance unqualified. An example of the document is below: <?xml version="1.0" encoding="utf-8" ?> <filingreceipt xmlns="http://www.disclosureusa.org/filingreceipt.xsd"> <cpofilingnumber>TX2004043037501</cpofilingnumber>...
2
10701
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 attribute and remove the containing node (and child nodes) if it has a certain value. I'm able to find the attributes using an XmlTextReader. Once found, can someone help me get the XPath at that point? I would then use this to remove the node from...
5
12280
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 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...
8
435
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 writing my own recursive parser to read the file, but I wonder if there is some method ready to use provided by the .NET which does the job! Thanks
4
4127
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" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:myurl-org:ns2 ...\Schemas\schema.xsd" type="Message"> <id root="7DC0FFE7-1224-4598-8F20-3B7662D416A1"/>
5
2397
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 precursor to moving our NT services, COM/DCOM, and client apps into C#) I'm wondering if there's something like this out there. For example, to use my CXMLNode class you could just do this: CXMLNode l_oRoot;
0
1067
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 levels like so: <node attr1="blahblah" attr2="blahblahblahblah"> <node attr1="flufffluff" attr2="shshshshsh"> <node attr1="cluckcluck" attr2="naynaynay" /> <node attr1="chillaladolads" attr2="lasfojelajdfljalsdf" /> <node attr1="eoijoawelkjladsf"...
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10212
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3962
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.