473,569 Members | 2,813 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Navigate and/or update an existing XML file

Hi all,

I'm new to .NET and XML and I have a question. Given an XML file, I want to
navigate its content and look for one or two particular elements to get their
values. At this point, it suffices to open the XML file for read-only access.

Once I have processed these values, I might need to update a bunch of
subelements of a certain element. For example, I may need to update the
Field Name attribute plus the DataField element value in Fields.

<Fields>
<Field Name="EMPLOYEE_ ID">
<DataField>EMPL OYEE_ID</DataField>
<rd:TypeName>Sy stem.Int64</rd:TypeName>
</Field>
<Field Name="LAST_NAME ">
<DataField>LAST _NAME</DataField>
<rd:TypeName>Sy stem.String</rd:TypeName>
</Field>
<Field Name="FIRST_NAM E">
<DataField>FIRS T_NAME</DataField>
<rd:TypeName>Sy stem.String</rd:TypeName>
</Field>
</Fields>

The thing is that I may not need to update this XML file. However, when I
need to, this XML file may be big and my question is whether I should use
XmlDocument for read and write purpose together with XPath expressions? Or
should I use XPathDocument for better performance?

Any other suggestions or ideas?

Thank you very much!
Nov 12 '05 #1
8 5778
Hello!
The thing is that I may not need to update this XML file. However, when I
need to, this XML file may be big and my question is whether I should use
XmlDocument for read and write purpose together with XPath expressions? Or
should I use XPathDocument for better performance?


That depends. XmlDocument is the slowest way to do it - if you are able
to do it using XPath & read-only, use XPathDocument. But if the file is
/really/ big (some MBytes) it's best to use XmlTextReader - it is not as
flexible as evaluating a simple XPath expression but the fastest way
(and your document does not look that complex - it should be easy)

<http://msdn2.microsoft .com/library/System.Xml.XmlT extReader>

If you need fast reading & writing and the data you edit does not depend
on anything else in the document (like "change last name of employee
42") you can use XmlTextReader and XmlTextWriter to "stream process" the
document:

<http://msdn2.microsoft .com/library/System.Xml.XmlT extWriter>
This could look like this (untested):

\\\

XmlTextReader r = new XmlTextReader(" file");
XmlTextWriter w = new XmlTextWriter(" tempfile");

string id = "42";
bool isField, isEmployeeField m, isTargetDataFie ld, isTargetEmploye e;

while( r.Read() ){
switch( r.NodeType ){
...
case XmlNodeType.Ele ment:
isField = r.LocalName.Equ als( "Field" );
w.WriteStartEle ment( r.Name );
isTargetDataFie ld = isEmployeeField &&
r.LocalName.Equ als("DataField" );
break;
...
case XmlNodeType.Att ribute:
isEmployeeField = isField && r.LocalName.Equ als("Name") &&
r.Value.Equals( "EMPLOYEE_I D");
w.WriteStartAtt ribute( r.Name );
break;
...
case XmlNodeType.Tex t:
isTargetEmploye e = isTargetDataFie ld && r.Value.Equals( "42");
....

}
}

///

--
Pascal Schmitt
Nov 12 '05 #2
Thank you for your help! Really appreciated!

The thing is that it is not always read-only access and the file may be a
few hundred kilo bytes. I'm not sure how slow XmlDocument can be.

Would you recommend that I simply use XmlTextReader to search for some
elements while reading in the file instead of using XPath and/or
XPathDocument? Then when I realize that I need to update the Xml file,
simply create a new Xml file using XmlTextWriter?

What I'm worried is that what I need to read (parse) first is near the end
of the Xml file and what I need to update is actually near the top of the Xml
file ...

Any suggestions are welcome. Thank you!
"Pascal Schmitt" wrote:
Hello!
The thing is that I may not need to update this XML file. However, when I
need to, this XML file may be big and my question is whether I should use
XmlDocument for read and write purpose together with XPath expressions? Or
should I use XPathDocument for better performance?


That depends. XmlDocument is the slowest way to do it - if you are able
to do it using XPath & read-only, use XPathDocument. But if the file is
/really/ big (some MBytes) it's best to use XmlTextReader - it is not as
flexible as evaluating a simple XPath expression but the fastest way
(and your document does not look that complex - it should be easy)

<http://msdn2.microsoft .com/library/System.Xml.XmlT extReader>

If you need fast reading & writing and the data you edit does not depend
on anything else in the document (like "change last name of employee
42") you can use XmlTextReader and XmlTextWriter to "stream process" the
document:

<http://msdn2.microsoft .com/library/System.Xml.XmlT extWriter>
This could look like this (untested):

\\\

XmlTextReader r = new XmlTextReader(" file");
XmlTextWriter w = new XmlTextWriter(" tempfile");

string id = "42";
bool isField, isEmployeeField m, isTargetDataFie ld, isTargetEmploye e;

while( r.Read() ){
switch( r.NodeType ){
...
case XmlNodeType.Ele ment:
isField = r.LocalName.Equ als( "Field" );
w.WriteStartEle ment( r.Name );
isTargetDataFie ld = isEmployeeField &&
r.LocalName.Equ als("DataField" );
break;
...
case XmlNodeType.Att ribute:
isEmployeeField = isField && r.LocalName.Equ als("Name") &&
r.Value.Equals( "EMPLOYEE_I D");
w.WriteStartAtt ribute( r.Name );
break;
...
case XmlNodeType.Tex t:
isTargetEmploye e = isTargetDataFie ld && r.Value.Equals( "42");
....

}
}

///

--
Pascal Schmitt

Nov 12 '05 #3
Hello!
Would you recommend that I simply use XmlTextReader to search for some
elements while reading in the file instead of using XPath and/or
XPathDocument? Then when I realize that I need to update the Xml
file,
simply create a new Xml file using XmlTextWriter?
No - the XmlReaders are not caching - you have to use the information
when you read it (if you don't save it on your own) if you want to
"skip" back to the beginning of a file you have to read it from the
beginning with a new XmlReader.

The thing is that it is not always read-only access and the file may
be a
few hundred kilo bytes. I'm not sure how slow XmlDocument can be.

What I'm worried is that what I need to read (parse) first is near the
end
of the Xml file and what I need to update is actually near the top of
the Xml
file ...


The "slow" bit of XmlDocument is that it parses the XML completely and
creates a full DOM-Tree in-memory. This is no problem, if your file is
just in the area of KBytes and you nead Random access.
So for your case I would recommend you to use XmlDocument with its
XPath-abilities for more flexibility and shorter Code (untested):

XmlDocument doc = new XmlDocument();
doc.Load("file" );
XmlElement e =
doc.SelectSingl eNode("/Fields/Field[@Name='EMPLOYEE _ID']/DataField[.='42']")
as XmlElement;
if( e == null ) throw new Exception();
XmlElement n =
doc.SelectSingl eNode("/Fields/Field[@Name='FIRST_NA ME']/DataField") as
XmlElement;
if( n == null ) throw new Excepttion();

// do something with the nodes

doc.Save("file" );

--
Pascal Schmitt
Nov 12 '05 #4
Your help and sample code are greatly appreciated and I will go ahead
experimenting with XmlDocument and XPath as suggested.

Thank you!
Jenny

"Pascal Schmitt" wrote:
Hello!
> Would you recommend that I simply use XmlTextReader to search for some
> elements while reading in the file instead of using XPath and/or
> XPathDocument? Then when I realize that I need to update the Xml
> file,
> simply create a new Xml file using XmlTextWriter?


No - the XmlReaders are not caching - you have to use the information
when you read it (if you don't save it on your own) if you want to
"skip" back to the beginning of a file you have to read it from the
beginning with a new XmlReader.

> The thing is that it is not always read-only access and the file may
> be a
> few hundred kilo bytes. I'm not sure how slow XmlDocument can be.
>
> What I'm worried is that what I need to read (parse) first is near the
> end
> of the Xml file and what I need to update is actually near the top of
> the Xml
> file ...


The "slow" bit of XmlDocument is that it parses the XML completely and
creates a full DOM-Tree in-memory. This is no problem, if your file is
just in the area of KBytes and you nead Random access.
So for your case I would recommend you to use XmlDocument with its
XPath-abilities for more flexibility and shorter Code (untested):

XmlDocument doc = new XmlDocument();
doc.Load("file" );
XmlElement e =
doc.SelectSingl eNode("/Fields/Field[@Name='EMPLOYEE _ID']/DataField[.='42']")
as XmlElement;
if( e == null ) throw new Exception();
XmlElement n =
doc.SelectSingl eNode("/Fields/Field[@Name='FIRST_NA ME']/DataField") as
XmlElement;
if( n == null ) throw new Excepttion();

// do something with the nodes

doc.Save("file" );

--
Pascal Schmitt

Nov 12 '05 #5
Hi Pascal

I've played with XmlDocument and XPath expressions and I seem to get what I
wanted so far. Thanks for your help again.

However, as I reach an Xml node and I'd like to create a new Xml element
with attribute and a child element, I do the followings:

XmlElement fieldElem = myXmlDocument.C reateElement("F ield");
XmlElement dataField = myXmlDocument.C reateElement("D ataField");
XmlText text = myXmlDocument.C reateTextNode(" Field 1");
fieldElem.Appen dChild(dataFiel d);
dataField.Appen dChild(text);
fields.AppendCh ild(fieldElem);

fieldElem.SetAt tribute("Name", "Field 1");

------------

The XML file shows

<Field Name="Field 1" xmlns="">
<DataField>Fiel d 1</DataField>
</Field>
Is there any way that I could get rid of the xmlns part? In other words I
want it to be just <Field Name="Field 1"> ... </Field>

I found that if I call SetAttribute() for an existing Xml element, it does
not add this annoying xmlns part. For some reasons, in my case, I can't seem
to get rid of it.

Please help! Thanks again!
Jenny

"Pascal Schmitt" wrote:
Hello!
> Would you recommend that I simply use XmlTextReader to search for some
> elements while reading in the file instead of using XPath and/or
> XPathDocument? Then when I realize that I need to update the Xml
> file,
> simply create a new Xml file using XmlTextWriter?


No - the XmlReaders are not caching - you have to use the information
when you read it (if you don't save it on your own) if you want to
"skip" back to the beginning of a file you have to read it from the
beginning with a new XmlReader.

> The thing is that it is not always read-only access and the file may
> be a
> few hundred kilo bytes. I'm not sure how slow XmlDocument can be.
>
> What I'm worried is that what I need to read (parse) first is near the
> end
> of the Xml file and what I need to update is actually near the top of
> the Xml
> file ...


The "slow" bit of XmlDocument is that it parses the XML completely and
creates a full DOM-Tree in-memory. This is no problem, if your file is
just in the area of KBytes and you nead Random access.
So for your case I would recommend you to use XmlDocument with its
XPath-abilities for more flexibility and shorter Code (untested):

XmlDocument doc = new XmlDocument();
doc.Load("file" );
XmlElement e =
doc.SelectSingl eNode("/Fields/Field[@Name='EMPLOYEE _ID']/DataField[.='42']")
as XmlElement;
if( e == null ) throw new Exception();
XmlElement n =
doc.SelectSingl eNode("/Fields/Field[@Name='FIRST_NA ME']/DataField") as
XmlElement;
if( n == null ) throw new Excepttion();

// do something with the nodes

doc.Save("file" );

--
Pascal Schmitt

Nov 12 '05 #6
Hi Jenny,

The xmlns field indicates the default namespace for this field. Since you
didn't set the namespace for this field, and the parent node namespace is
set, the xmlns is automatically generated to indicate the default namespace
for this field is empty.

You can specify the qualified name and namespace URI for the element when
creating like the following.

XmlElement fieldElem = myXmlDocument.C reateElement("F ield",
"www.parentnode ns.com");

If the namespace "www.parentnode ns.com" is the same as parent node
namespace, the xmlns will be omit automantically.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 12 '05 #7
Thanks, Kevin. I actually figured it out myself right after I posted my
problem. Thanks anyway though because this confirms what I think. :-)

Jenny
"Kevin Yu [MSFT]" wrote:
Hi Jenny,

The xmlns field indicates the default namespace for this field. Since you
didn't set the namespace for this field, and the parent node namespace is
set, the xmlns is automatically generated to indicate the default namespace
for this field is empty.

You can specify the qualified name and namespace URI for the element when
creating like the following.

XmlElement fieldElem = myXmlDocument.C reateElement("F ield",
"www.parentnode ns.com");

If the namespace "www.parentnode ns.com" is the same as parent node
namespace, the xmlns will be omit automantically.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 12 '05 #8
You're welcome, Jenny.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 12 '05 #9

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

Similar topics

16
16984
by: Philip Boonzaaier | last post by:
I want to be able to generate SQL statements that will go through a list of data, effectively row by row, enquire on the database if this exists in the selected table- If it exists, then the colums must be UPDATED, if not, they must be INSERTED. Logically then, I would like to SELECT * FROM <TABLE> WHERE ....<Values entered here>, and then...
2
1323
by: Doug Bell | last post by:
Hi I have an application where I need to Update an XML file. The source is an Access DB. The Application imports new records from the Access DB into a DataSet and then needs to update the XML File. The problem I have is that WriteXML overwrites the existing XML file so on subsequent run only records that are new since the previous run...
1
5285
by: Joe Bond | last post by:
Hi. I have a simple MS Access 2000 form in which I enter some customer data. When the address field is entered I need to see if a duplicate record exists. I need to know this *right away* before the remaining fields are filled out, so I'm trying to call a function on the Address_LostFocus() event which will do the lookup. If a match is found,...
0
5805
by: M. David Johnson | last post by:
I cannot get my OleDbDataAdapter to update my database table from my local dataset table. The Knowledge Base doesn't seem to help - see item 10 below. I have a Microsoft Access 2000 database which indexes computer magazine articles for personal reference. I am developing a Visual Basic.NET program whose sole purpose is to enter new...
8
2765
by: robert | last post by:
Hello, I want to put (incrementally) changed/new files from a big file tree "directly,compressed and password-only-encrypted" to a remote backup server incrementally via FTP,SFTP or DAV.... At best within a closed algorithm inside Python without extra shell tools. (The method should work with any protocol which allows somehow read, write...
2
17946
by: Ryan Ramsey | last post by:
I have been chasing this one down for a week and have narrowed it down to a machine issue. I have the following code: webBrowser.Navigate(http://finao.net/post_dkp.php?database=40); Basically all this script does is create an xml output file. After the navigate, the function stops and is triggered again when...
4
7376
by: MN | last post by:
I have to import a tab-delimited text file daily into Access through a macro. All of the data needs to be added to an existing table. Some of the data already exists but may be updated by the imported text file. I can update the data through an update query or append the entire import table through an append query. Is there a way to combine...
5
23409
by: timnels | last post by:
I have a web browser control that I'd like to point at a HTML file in my installation directory. I am doing something like: string path = Path.GetDirectoryName( Assembly.GetExecutingAssembly().GetModules() .FullyQualifiedName) + "\\howdoi.htm"; webBrowser1.Navigate(path); What do I need to do to form the correct URI string for a local...
0
7618
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...
0
7926
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. ...
0
6287
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...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5223
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...
0
3657
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...
0
3647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
946
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...

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.