473,756 Members | 3,482 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Read XML - Need help please!

Hi there,

I have some problems when reading XML file.

1. First this, is what i did, cause i can't seem to read "sub elements or
tags" values, so i place those values into attributes like this.

Before:
----------

<?xml version="1.0" encoding="utf-8"?>
<MyConfig>
<Device Type="A1">
<Open />
<EstablishDevic e>
<DeviceName>Tit an 12</DeviceName>
<DeviceLength>8 </DeviceLength>
</EstablishDevice >
<Reset>
<Slot>0</Slot>
</Reset>
</Device>
<Device Type="A2">
<EstablishDevic e>
<DeviceName>Tit an 13</DeviceName>
<DeviceLength>8 </DeviceLength>
</EstablishDevice >
<Reset>
<Slot>1</Slot>
</Device>
</MyConfig>

After:
--------

<?xml version="1.0" encoding="utf-8"?>
<MyConfig>
<Device Type="A1">
<Open />
<EstablishDevic e Name="Titan 12" Length="8" />
<Reset Slot="0" />
</Device>
<Device Type="A2">
<Open />
<EstablishDevic e Name="Titan 13" Length="8" />
<Reset Slot="1" />
</Device>
</MyConfig>

So this is how my C# codes look like (but i think it is quite of wrong!)

C# - Read XML Tag + Attributes + Processing:
------------------------------------------------------

// strpath is the location of the xml file
XmlTextReader xmlreader = new XmlTextReader(s trPath);

// Create instance of MyLibrary
_library = new MyLibrary();

string sName = string.Empty;

while (xmlreader.Read ())
{
switch (xmlreader.Node Type)
{
case XmlNodeType.Ele ment:
//
//sName = xmlreader.Name;
if (xmlreader.Name .Equals("Device "))
{
lstResult.Items .Add("Type of Reader: " +
xmlreader.GetAt tribute("Type") );
lstResult.Items .Add("Build in progress ...");
}
if (xmlreader.Name .Equals("Open") )
{
try
{
// MyLibrary Open Method
_library.Open() ;
lstResult.Items .Add("OpenDevic e is success");
}
catch (Exception e)
{
lstResult.Items .Add("Open is not success" + re.Message);
}
}

if (xmlreader.Name .Equals("Establ ishDevice"))
{
string deviceName = xmlreader.GetAt tribute("Name") ;
int deviceLength = Int32.Parse(xml reader.GetAttri bute("Length")) ;

try
{
// Establish hardware connection
_library.Establ ishDevice(devic eName, deviceLength);
lstResult.Items .Add("Establish Device " +
xmlreader.GetAt tribute("Name") + " " + xmlreader.GetAt tribute("Length ") + "
is successfull!");
}
catch (Exception e)
{
lstResult.Items .Add("Error: " + e.Message);
}
}

if (xmlreader.Name .Equals("Reset" ))
{
short slotNumber = Int16.Parse(xml reader.GetAttri bute("Slot"));

try
{
// Reset the hardware before used
_library.Reset( slotNumber);
lstResult.Items .Add("Reset Device at Slot " +
xmlreader.GetAt tribute("Slot") + " is successfull!");
}
catch (Exception e)
{
lstResult.Items .Add("Error: " + e.Message);
}
}
break;
}
}
}

I really felt weird with the way i do. Is XPath a better technique to get
values directly? Just say, if i have 1000 lines of xml code, it is going to
read line by line even it does not use it. You get my meaning!

Now is my problem. I want to test my data which looks like below (just want
to avoid attributes for a while).

Assuming:

.....
.....
<Reset Slot="1" />
<!-- Add-on -->
</Device>
<Command id="A001">
<Slot Type="0">
<DataIn>1234567 8</DataIn>
<DataOut />
</Slot>
</Command>
<Command id="A002">
<Slot Type="0">
<DataIn />
<!-- Expect data out to be written here -->
<DataOut></DataOut>
</Slot>
</Command>
....
....
</MyConfig>

So now how do i read those values from DataIn?

I need to place some identification at Command, so i can know which command
tag to write the dataout.

Any help please? I hope you understand what is the problem here. If you
think there is a better way, please let me know!

Thanks.
--
Regards,
Chua Wen Ching
Visit us at http://www.necoders.com
Nov 16 '05 #1
1 3441
I would recommend using DOM(XmlDocument ) if the document is not huge.
Because it is easier, especially in this context of reading special nodes.
XmlDocument doc = new XmlDocument();
doc.Load(strPat h);
To get the first "DataIn" element:
// ASSUMING "Command" is direct descendant of root.
XmlNode node =
doc.DocumentEle ment.SelectSing leNode("Command[@id='A001']/Slot/DataIn");
Console.WriteLi ne(node.InnerTe xt);

If you need more help, please explain exactly what you are trying to do.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Chua Wen Ching" <ch************ @nospam.hotmail .com> wrote in message
news:10******** *************** ***********@mic rosoft.com...
Hi there,

I have some problems when reading XML file.

1. First this, is what i did, cause i can't seem to read "sub elements or
tags" values, so i place those values into attributes like this.

Before:
----------

<?xml version="1.0" encoding="utf-8"?>
<MyConfig>
<Device Type="A1">
<Open />
<EstablishDevic e>
<DeviceName>Tit an 12</DeviceName>
<DeviceLength>8 </DeviceLength>
</EstablishDevice >
<Reset>
<Slot>0</Slot>
</Reset>
</Device>
<Device Type="A2">
<EstablishDevic e>
<DeviceName>Tit an 13</DeviceName>
<DeviceLength>8 </DeviceLength>
</EstablishDevice >
<Reset>
<Slot>1</Slot>
</Device>
</MyConfig>

After:
--------

<?xml version="1.0" encoding="utf-8"?>
<MyConfig>
<Device Type="A1">
<Open />
<EstablishDevic e Name="Titan 12" Length="8" />
<Reset Slot="0" />
</Device>
<Device Type="A2">
<Open />
<EstablishDevic e Name="Titan 13" Length="8" />
<Reset Slot="1" />
</Device>
</MyConfig>

So this is how my C# codes look like (but i think it is quite of wrong!)

C# - Read XML Tag + Attributes + Processing:
------------------------------------------------------

// strpath is the location of the xml file
XmlTextReader xmlreader = new XmlTextReader(s trPath);

// Create instance of MyLibrary
_library = new MyLibrary();

string sName = string.Empty;

while (xmlreader.Read ())
{
switch (xmlreader.Node Type)
{
case XmlNodeType.Ele ment:
//
//sName = xmlreader.Name;
if (xmlreader.Name .Equals("Device "))
{
lstResult.Items .Add("Type of Reader: " +
xmlreader.GetAt tribute("Type") );
lstResult.Items .Add("Build in progress ...");
}
if (xmlreader.Name .Equals("Open") )
{
try
{
// MyLibrary Open Method
_library.Open() ;
lstResult.Items .Add("OpenDevic e is success");
}
catch (Exception e)
{
lstResult.Items .Add("Open is not success" + re.Message);
}
}

if (xmlreader.Name .Equals("Establ ishDevice"))
{
string deviceName = xmlreader.GetAt tribute("Name") ;
int deviceLength = Int32.Parse(xml reader.GetAttri bute("Length")) ;

try
{
// Establish hardware connection
_library.Establ ishDevice(devic eName, deviceLength);
lstResult.Items .Add("Establish Device " +
xmlreader.GetAt tribute("Name") + " " + xmlreader.GetAt tribute("Length ") +
"
is successfull!");
}
catch (Exception e)
{
lstResult.Items .Add("Error: " + e.Message);
}
}

if (xmlreader.Name .Equals("Reset" ))
{
short slotNumber = Int16.Parse(xml reader.GetAttri bute("Slot"));

try
{
// Reset the hardware before used
_library.Reset( slotNumber);
lstResult.Items .Add("Reset Device at Slot " +
xmlreader.GetAt tribute("Slot") + " is successfull!");
}
catch (Exception e)
{
lstResult.Items .Add("Error: " + e.Message);
}
}
break;
}
}
}

I really felt weird with the way i do. Is XPath a better technique to get
values directly? Just say, if i have 1000 lines of xml code, it is going
to
read line by line even it does not use it. You get my meaning!

Now is my problem. I want to test my data which looks like below (just
want
to avoid attributes for a while).

Assuming:

....
....
<Reset Slot="1" />
<!-- Add-on -->
</Device>
<Command id="A001">
<Slot Type="0">
<DataIn>1234567 8</DataIn>
<DataOut />
</Slot>
</Command>
<Command id="A002">
<Slot Type="0">
<DataIn />
<!-- Expect data out to be written here -->
<DataOut></DataOut>
</Slot>
</Command>
...
...
</MyConfig>

So now how do i read those values from DataIn?

I need to place some identification at Command, so i can know which
command
tag to write the dataout.

Any help please? I hope you understand what is the problem here. If you
think there is a better way, please let me know!

Thanks.
--
Regards,
Chua Wen Ching
Visit us at http://www.necoders.com

Nov 16 '05 #2

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

Similar topics

3
12770
by: Shaun Merrill | last post by:
Hey, here is my code. I am trying to read a file into a byte array. Please show me how this can work. Obviously I need to read into a dynamic array because it could read any file. So why does VB.NET give me the ability to read into a Byte Array if it doesn't allow me to use a variable sized array? Dim i As Short = FreeFile() FileSystem.FileOpen(i, Filename, OpenMode.Binary, OpenAccess.Read, OpenShare.Default) Dim iByteArray() As Byte
3
4330
by: Udhay | last post by:
Sir, I want to read the data of an audio file in c++ (Windows). What is the API which helps to read the data of an audio file. I want to read BitRate,Audio Sample Size,Audio Sample rate and Channel udhay
5
3463
by: =?Utf-8?B?bXBhaW5l?= | last post by:
Hello, I am completely lost as to why I can't update a DropDownList inside a DetailsView after I perform an insert into an object datasource. I tried to simply it down to the core demostration: default.aspx:
3
12495
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Hi I have an xsd that I want to save as an XML string to store in a DB I can save as a physical file using xsd.WriteXml(@"C:\Temp\Junk\junk.xml"); But I am unable to save to a string so I can write string to a db I tried to a MemoryStream but it seems to be empty ??? There is data
2
5348
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Hi Is there any way to Read an INIFile from a string or Stream instead of a physical file ??? I want to read the INIFile into a string then store in a db but when I read the string from the db or save string to the db I don't want to have to copy the string to a file to use the WritePrivateProfileString and GetPrivateProfileString. Is there a way around this instead of writing my own class to operate on a string or stream ???
3
2407
by: Laura | last post by:
Hi: ¿How can I read a file on the client side without loading it to the server?
2
2171
by: Riak | last post by:
Hellow Helpers: I am doing data entry job manually and data is huge. Now I was told to write/get some sort of program/script which can do this job quickly, otherwise I will loose job. I am good computer user but far away from programming, however I can make minor/little changes into script/program e.g. if it reads one records, I can update record name to read or ask to read next record. This is all my knowledge/skills about programming. Here...
0
10046
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
9886
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9857
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9722
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
8723
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
5155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3817
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
3
2677
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.