473,729 Members | 2,079 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to replace attribute's special characters using XMLTextReader

Hi all,
I ran into a problem where my XMLTextReader fails on .Read() when I have "<" character in one of the attribute's values. What I am trying to do is replace illegal characters ("<", "&" , etc.) with legal stuff ("&lt;", "&amp;", etc.), before I send the XML text to a SQL Server stored procedure. Currently, I am using XMLTextReader and StringWriter to do this, here is the piece of code that fails:
----------------------------------------------------------
With .XMLTextReaderO bj
Do While (.Read() = True)
Select Case .NodeType
Case XmlNodeType.Ele ment
Me.XMLStringWri terObj.Write("< " & .Name)
If .IsEmptyElement = True Then
EndTagStr = "></" & .Name & ">"
If .HasAttributes = True Then
While .MoveToNextAttr ibute()
Me.XMLStringWri terObj.Write(" {0}='{1}'", .Name, Replace(Replace (Replace(Replac e(Replace(.Valu e, Chr(38), "&amp;"), Chr(60), "&lt;"), Chr
(62), "&gt;"), Chr(34), "&quot;"), Chr(39), "&apos;"))
End While
End If
Else
EndTagStr = ">"
If .HasAttributes = True Then
While .MoveToNextAttr ibute()
Me.XMLStringWri terObj.Write(" {0}='{1}'", .Name, Replace(Replace (Replace(Replac e(Replace(.Valu e, Chr(38), "&amp;"), Chr(60), "&lt;"), Chr
(62), "&gt;"), Chr(34), "&quot;"), Chr(39), "&apos;"))
End While
End If
End If
Me.XMLStringWri terObj.Write(En dTagStr)
Case XmlNodeType.Tex t
Me.XMLStringWri terObj.Write(Re place(Replace(R eplace(Replace( Replace(.Value, Chr(38), "&amp;"), Chr(60), "&lt;"), Chr(62), "&gt;"), Chr(34), "&quot;"),
Chr(39), "&apos;"))
Case XmlNodeType.End Element
Me.XMLStringWri terObj.Write("</" & .Name & ">")
End Select
Loop
.Close()
End With

Any suggestions appreciated
Thanks
Goran
Jan 21 '07 #1
12 11547
Hi Goran,

The XmlTextReader cannot accept nodes that contains reserved words. In this
case, it mean the source Xml file you're trying to read from is invalid.
The reserved chars has to be escaped before writing to a text file. Could
you please let me know where the source xml file come from? We might solve
the problem with the following options:

1. Make the source xml file valid.
2. Use a plain TextReader to read the file for escaping.

Kevin Yu
Microsoft Online Community Support

=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====

(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Jan 22 '07 #2
Goran Djuranovic wrote:
I ran into a problem where my XMLTextReader *fails* on /.Read()/ when I
have "<" character in one of the attribute's values. What I am trying to
do is replace illegal characters ("<", "&" , etc.) with legal stuff
("&lt;", "&amp;", etc.), before I send the XML text to a SQL Server
stored procedure.
If a literal '<' or a literal '&' were allowed in an attribute value
then you could send the alleged XML to SQL server directly. But what you
have is not well-formed XML so neither SQL server nor Xml(Text)Reader
will accept it as XML. You need to use non-XML tools to fix the input,
any XML parser will reject not well-formed markup.
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Jan 22 '07 #3
Hi Kevin,
The XML file is coming from the interface engine. It will contain attributes
such as Value="<30%" or Comment="Run more & eat healthy". The other side
does not want to well-format it, so no choice there.

One way I can do this is to use regular expressions and replace illegal XML
characters within any double-quote-enclosed string, being that attributes
are double-quote eclosed, but I wanted to know if there is any other way.

What do you suggest and do you have any specific code example that would do
something similar?

Thanks a lot.
Goran Djuranovic
"Kevin Yu [MSFT]" <v-****@online.mic rosoft.comwrote in message
news:WF******** ******@TK2MSFTN GHUB02.phx.gbl. ..
Hi Goran,

The XmlTextReader cannot accept nodes that contains reserved words. In
this
case, it mean the source Xml file you're trying to read from is invalid.
The reserved chars has to be escaped before writing to a text file. Could
you please let me know where the source xml file come from? We might solve
the problem with the following options:

1. Make the source xml file valid.
2. Use a plain TextReader to read the file for escaping.

Kevin Yu
Microsoft Online Community Support

=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====

(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Jan 22 '07 #4
Hi Martin,
I kind of new that I would need a non-XML tool or procedure in order to do
this, but I don't want to reinvent the wheel if there is one outthere. :-)
In my response the Kevin (above), I said I can do this by using regular
expressions and replacing illegal XML
characters within any double-quote-enclosed string (being that attributes
are double-quote eclosed in my case), but I wanted to know if there is any
other way.

Any other suggestions on what I should use or how I should approach this?

Thanks a lot.
Goran Djuranovic

"Martin Honnen" <ma*******@yaho o.dewrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
Goran Djuranovic wrote:
>I ran into a problem where my XMLTextReader *fails* on /.Read()/ when I
have "<" character in one of the attribute's values. What I am trying to
do is replace illegal characters ("<", "&" , etc.) with legal stuff
("&lt;", "&amp;", etc.), before I send the XML text to a SQL Server
stored procedure.

If a literal '<' or a literal '&' were allowed in an attribute value then
you could send the alleged XML to SQL server directly. But what you have
is not well-formed XML so neither SQL server nor Xml(Text)Reader will
accept it as XML. You need to use non-XML tools to fix the input, any XML
parser will reject not well-formed markup.
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/

Jan 22 '07 #5
Goran Djuranovic wrote:
The XML file is coming from the interface engine. It will contain attributes
such as Value="<30%" or Comment="Run more & eat healthy". The other side
does not want to well-format it, so no choice there.
Then what the other side sends is not XML at all. You will have a hard
time trying to fix the mess they send you.
One way I can do this is to use regular expressions and replace illegal XML
characters within any double-quote-enclosed string, being that attributes
are double-quote eclosed, but I wanted to know if there is any other way.
As said, XML tools will not work if someone sends not well-formed
markup. You can try to fix it with regular expressions but unescaped &
and < are not only a problem in attribute values but also in element
content.

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Jan 22 '07 #6
I understand that, but fortunatelly, our side cares about fixing attribute
mess. In case of any "other" mess, the file is marked as invalid. :-)

Anyway, I am asking for any suggestions to fix the attribute mess a not the
explanations of if the XML file is bad and why it is bad.

Thanks a lot.
Goran Djuranovic
"Martin Honnen" <ma*******@yaho o.dewrote in message
news:e2******** ******@TK2MSFTN GP02.phx.gbl...
Goran Djuranovic wrote:
>The XML file is coming from the interface engine. It will contain
attributes such as Value="<30%" or Comment="Run more & eat healthy". The
other side does not want to well-format it, so no choice there.

Then what the other side sends is not XML at all. You will have a hard
time trying to fix the mess they send you.
>One way I can do this is to use regular expressions and replace illegal
XML characters within any double-quote-enclosed string, being that
attributes are double-quote eclosed, but I wanted to know if there is any
other way.

As said, XML tools will not work if someone sends not well-formed markup.
You can try to fix it with regular expressions but unescaped & and < are
not only a problem in attribute values but also in element content.

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/

Jan 22 '07 #7
As the file in question is not a well-formed xml document, a xml group like
this is not relevant -- do try better luck at a general text-editing forum.

Cheers,
Dimitre Novatchev

"Goran Djuranovic" <go************ **@newsgroups.n ospamwrote in message
news:O%******** *******@TK2MSFT NGP03.phx.gbl.. .
Hi Martin,
I kind of new that I would need a non-XML tool or procedure in order to do
this, but I don't want to reinvent the wheel if there is one outthere. :-)
In my response the Kevin (above), I said I can do this by using regular
expressions and replacing illegal XML
characters within any double-quote-enclosed string (being that attributes
are double-quote eclosed in my case), but I wanted to know if there is any
other way.

Any other suggestions on what I should use or how I should approach this?

Thanks a lot.
Goran Djuranovic

"Martin Honnen" <ma*******@yaho o.dewrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
>Goran Djuranovic wrote:
>>I ran into a problem where my XMLTextReader *fails* on /.Read()/ when I
have "<" character in one of the attribute's values. What I am trying to
do is replace illegal characters ("<", "&" , etc.) with legal stuff
("&lt;", "&amp;", etc.), before I send the XML text to a SQL Server
stored procedure.

If a literal '<' or a literal '&' were allowed in an attribute value then
you could send the alleged XML to SQL server directly. But what you have
is not well-formed XML so neither SQL server nor Xml(Text)Reader will
accept it as XML. You need to use non-XML tools to fix the input, any XML
parser will reject not well-formed markup.
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/


Jan 22 '07 #8
Hi Dimitre,
So what you are saying is that this forum is relevant only for well-formed
XML files???
Ha, ha, ha.... :-) You are a funny man.

Now, if you have any suggestions on how to best solve this problem, please
respond. Suggestions are very appreciated.Oth erwise, stand by. :-)
FYI, the same question is also cross-posted on VB.NET forum, but here I got
a better response.

Thanks
Goran Djuranovic
"Dimitre Novatchev" <dn********@som ewhere.comwrote in message
news:eS******** *****@TK2MSFTNG P06.phx.gbl...
As the file in question is not a well-formed xml document, a xml group
like this is not relevant -- do try better luck at a general text-editing
forum.

Cheers,
Dimitre Novatchev

"Goran Djuranovic" <go************ **@newsgroups.n ospamwrote in message
news:O%******** *******@TK2MSFT NGP03.phx.gbl.. .
>Hi Martin,
I kind of new that I would need a non-XML tool or procedure in order to
do this, but I don't want to reinvent the wheel if there is one outthere.
:-) In my response the Kevin (above), I said I can do this by using
regular expressions and replacing illegal XML
characters within any double-quote-enclosed string (being that attributes
are double-quote eclosed in my case), but I wanted to know if there is
any other way.

Any other suggestions on what I should use or how I should approach this?

Thanks a lot.
Goran Djuranovic

"Martin Honnen" <ma*******@yaho o.dewrote in message
news:%2******* *********@TK2MS FTNGP02.phx.gbl ...
>>Goran Djuranovic wrote:

I ran into a problem where my XMLTextReader *fails* on /.Read()/ when I
have "<" character in one of the attribute's values. What I am trying
to do is replace illegal characters ("<", "&" , etc.) with legal stuff
("&lt;", "&amp;", etc.), before I send the XML text to a SQL Server
stored procedure.

If a literal '<' or a literal '&' were allowed in an attribute value
then you could send the alleged XML to SQL server directly. But what you
have is not well-formed XML so neither SQL server nor Xml(Text)Reader
will accept it as XML. You need to use non-XML tools to fix the input,
any XML parser will reject not well-formed markup.
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/



Jan 23 '07 #9
Hi Goran,

As Martin mentioned, the only way is to use regular expression or some
other techniques like finding char by char to replace these invalid chars
to make the Xml well-formed.

HTH. If anything is unclear, please feel free to let me know.

Kevin Yu
Microsoft Online Community Support
=============== =============== =============== =====

(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Jan 24 '07 #10

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

Similar topics

17
47819
by: Pikkel | last post by:
i'm looking for a way to replace special characters with characters without accents, cedilles, etc.
9
3718
by: Jiho Han | last post by:
Suppose I have an xml fragment like: <mother> <child name="Bob" sex="M"/> <child name="Jane" sex="F"/> ... </mother> If I wanted to replace the <mother> element to <father> element, what is the fastest or most efficient way to do this?
2
10700
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...
12
6323
by: ~~~ .NET Ed ~~~ | last post by:
Hi, I have a standalone XML file (with the appropriate xml document header) that works fine when I load it using XmlDocument. I can have child elements like this without problems: <SomeChildElement type="c" href="There.aspx?id=5" /> But as soon as I change it to something like this: <SomeChildElement type="c" href="There.aspx?id=5&amp;t=m" />
1
4430
by: soupaman | last post by:
Im trying to output some filtered xml using the xmlTextReader I know the code and commenting needs cleaned up and eventually plan to add the values to a dataset. currently what this is doing is matching the filters, runs into the response.write and outputs nothing. I've used the dbgclr to verify that the filters are matching and it is hitting the response.write what I want it to do is match the filters (an array) and output the value of...
1
5456
by: RJN | last post by:
Hi I'm using XMLTextReader to parse the contents of XML. I have issues when the xml content itself has some special characters like & ,> etc. <CompanyName>Johnson & Jhonson</CompanyName> <EmployeeStrength>> 1000</EmployeeStrength> When I do a Xmltextreader.read() and then check the contents of the xml node by XmltextReader.ReadString(), I get an exception when I have
16
6163
by: BBM | last post by:
This is so bizarre I hesitate to post it, but I need to get this working. My code looks like this... Private Const cmdTestResourcesSel = "SELECT * FROM TResources" & _ " WHERE Scenario = @Scenario" Dim cmdstr as String cmdstr = cmdTestResourcesSel
4
7645
by: JimmyW | last post by:
Hello, How characters é and ü should be coded into App.Config file? For Example & must be converted to &amp; but how those two characters é (e with dot) and ü (German u) should be coded? Can anyone help? Cheers!
3
3321
by: Goran Djuranovic | last post by:
Hi all, I ran into a problem where my XMLTextReader fails on .Read() when I have "<" character in one of the attribute's values. What I am trying to do is replace illegal characters ("<", "&" , etc.) with legal stuff ("&lt;", "&amp;", etc.), before I send the XML text to a SQL Server stored procedure. Currently, I am using XMLTextReader and StringWriter to do this, here is the piece of code that fails:...
6
3094
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello, I have some XML that is returned to my application from another vendor that I cannot change before it gets to me. I can only alter it after it gets to my application. That being said, I am having a problem loading the XML correctly into my app. Here is the code: ==================================== Dim sPaymentXML as String
0
8928
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
8766
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
9291
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...
0
9158
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
8160
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...
1
6722
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4799
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2698
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2171
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.