473,857 Members | 1,830 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to find and replace sequences of elements

Given the following XML document:

<text>
<p>
<w>Ronaldo</w>
<w>scoredw>
<w>the</w>
<w>1</w>
<c>:</c>
<w>1</w>
<w>opener</w>
</p>
...
<text>

I need to

1) find patterns like <w>...</w><c>:</c><w>...</w>, i.e. any
'w'-element, followed by a 'c'-element with text ':', followed by any
'w'-element
2) replace this pattern with <w>...:...</w>, i.e. a single element in
which the text of the found elements is aligned

Right now, I am doing this with the following stylesheet:

-----------------------------------------------------------
<xsl:styleshe et version="1.0"
xmlns:xsl="http ://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>

<!-- go through the whole document, copy everything -->
<xsl:template match="/ | @* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>

<!-- for c-elements whose text is ':'... -->
<xsl:template match="//c[text()=':']">
<xsl:if test="name(prec eding-sibling::*[1])='w' and
name(following-sibling::*[1])='w'">
<!-- ... make a new element and put the text of the matching
pattern inside -->
<w type='score'>
<xsl:value-of select="precedi ng-sibling::*[1]/text()"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="followi ng-sibling::*[1]/text()"/>
</w>
</xsl:if>
</xsl:template>

<!-- make sure not to copy w-elements that have been taken care of by
the former template -->
<xsl:template match="//w[name(following-sibling::*[1])='c' and
following-sibling::*[1]/text()=':' and
name(following-sibling::*[2])='w']">
</xsl:template>
<xsl:template match="//w[name(preceding-sibling::*[1])='c' and
preceding-sibling::*[1]/text()=':' and
name(preceding-sibling::*[2])='w']">
</xsl:template>
</xsl:stylesheet>
-----------------------------------------------------------

This works OK but it looks so awkward! What's more: if the patterns I
want to replace get longer, it becomes increasingly difficult to take
care of all the things that must not be copied a second time (i.e. the
last to templates in the above). Can anybody point me to a more elegant
way of doing this?

Thanks very much,

Thomas

Sep 6 '05 #1
9 1968
Be********@gmai l.com <Be********@gma il.com> wrote:
Given the following XML document:

<text>
<p>
<w>Ronaldo</w>
<w>scoredw>
<w>the</w>
<w>1</w>
<c>:</c>
<w>1</w>
<w>opener</w>
</p>
...
<text>

I need to

1) find patterns like <w>...</w><c>:</c><w>...</w>, i.e. any
'w'-element, followed by a 'c'-element with text ':', followed by any
'w'-element
2) replace this pattern with <w>...:...</w>, i.e. a single element in
which the text of the found elements is aligned

Right now, I am doing this with the following stylesheet:

-----------------------------------------------------------
<xsl:styleshe et version="1.0"
xmlns:xsl="http ://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>

<!-- go through the whole document, copy everything -->
<xsl:template match="/ | @* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>

<!-- for c-elements whose text is ':'... -->
<xsl:template match="//c[text()=':']">
<xsl:if test="name(prec eding-sibling::*[1])='w' and
name(following-sibling::*[1])='w'">
<!-- ... make a new element and put the text of the matching
pattern inside -->
<w type='score'>
<xsl:value-of select="precedi ng-sibling::*[1]/text()"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="followi ng-sibling::*[1]/text()"/>
</w>
</xsl:if>
</xsl:template>

<!-- make sure not to copy w-elements that have been taken care of by
the former template -->
<xsl:template match="//w[name(following-sibling::*[1])='c' and
following-sibling::*[1]/text()=':' and
name(following-sibling::*[2])='w']">
</xsl:template>
<xsl:template match="//w[name(preceding-sibling::*[1])='c' and
preceding-sibling::*[1]/text()=':' and
name(preceding-sibling::*[2])='w']">
</xsl:template>
</xsl:stylesheet>
-----------------------------------------------------------

This works OK but it looks so awkward! What's more: if the patterns I
want to replace get longer, it becomes increasingly difficult to take
care of all the things that must not be copied a second time (i.e. the
last to templates in the above). Can anybody point me to a more elegant
way of doing this?

Thanks very much,

Thomas


Key insight is "split" and then "join". In extended Bash shell,
a=`< file.xml`
set -- "${a|-</w>[[:space:]]*<c>:</c>[[:space:]]*<w>}"
echo "${*|,:}"
where
${var|-regex} splits the string on 'regex'
${list|,sep} joins the elements using 'sep' string.

You can do the same thing in Python also.

--
William Park <op**********@y ahoo.ca>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
http://freshmeat.net/projects/bashdiff/
Sep 6 '05 #2

<Be********@gma il.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
Given the following XML document:

<text>
<p>
<w>Ronaldo</w>
<w>scoredw>
<w>the</w>
<w>1</w>
<c>:</c>
<w>1</w>
<w>opener</w>
</p>
...
<text>

I need to

1) find patterns like <w>...</w><c>:</c><w>...</w>, i.e. any
'w'-element, followed by a 'c'-element with text ':', followed by any
'w'-element
2) replace this pattern with <w>...:...</w>, i.e. a single element in
which the text of the found elements is aligned

Right now, I am doing this with the following stylesheet:

-----------------------------------------------------------
<xsl:styleshe et version="1.0"
xmlns:xsl="http ://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>

<!-- go through the whole document, copy everything -->
<xsl:template match="/ | @* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>

<!-- for c-elements whose text is ':'... -->
<xsl:template match="//c[text()=':']">
<xsl:if test="name(prec eding-sibling::*[1])='w' and
name(following-sibling::*[1])='w'">
<!-- ... make a new element and put the text of the matching
pattern inside -->
<w type='score'>
<xsl:value-of select="precedi ng-sibling::*[1]/text()"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="followi ng-sibling::*[1]/text()"/>
</w>
</xsl:if>
</xsl:template>

<!-- make sure not to copy w-elements that have been taken care of by
the former template -->
<xsl:template match="//w[name(following-sibling::*[1])='c' and
following-sibling::*[1]/text()=':' and
name(following-sibling::*[2])='w']">
</xsl:template>
<xsl:template match="//w[name(preceding-sibling::*[1])='c' and
preceding-sibling::*[1]/text()=':' and
name(preceding-sibling::*[2])='w']">
</xsl:template>
</xsl:stylesheet>
-----------------------------------------------------------

This works OK but it looks so awkward! What's more: if the patterns I
want to replace get longer, it becomes increasingly difficult to take
care of all the things that must not be copied a second time (i.e. the
last to templates in the above). Can anybody point me to a more elegant
way of doing this?

Use the "Tree Visitor" pattern like this:

<xsl:styleshe et version="1.0"
xmlns:xsl="http ://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="ye s"/>

<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="node()[1]"/>
</xsl:copy>
<xsl:apply-templates select="followi ng-sibling::node()[1]"/>
</xsl:template>

<xsl:template match="w[following-sibling::*[1][self::c]
and
following-sibling::c[1]=':'
and
following-sibling::*[2][self::w]
]">
<w>
<xsl:value-of select=
"concat(.,follo wing-sibling::*[1],following-sibling::*[2])"/>
</w>
<xsl:apply-templates select=
"following-sibling::*[2]/following-sibling::node()[1]"/>
</xsl:template>

</xsl:stylesheet>

When this transformation is applied on your source xml (corrected to be at
least well-formed):

<text>
<p>
<w>Ronaldo</w>
<w>scoredw</w>
<w>the</w>
<w>1</w>
<c>:</c>
<w>1</w>
<w>opener</w>
</p>
...
</text>

the wanted result is produced:

<text>
<p>
<w>Ronaldo</w>
<w>scoredw</w>
<w>the</w>
<w>1:1</w>
<w>opener</w>
</p>
...
</text>

Here I use a variation of the identity rule that only applies templates to
one node at a time. This results in achieving maximum flexibility in
processing the nodes of the xml document really sequentially.
Hope this helped.

Cheers,
Dimitre Novatchev
Sep 6 '05 #3
Thanks, Dimitre, this is very, very helpful!
Just one more question: if the sequence pattern I want to replace
consists of, (e.g.) five elements (and not three like in the example),
I would
1) change the match-value of the last template accordingly and
2) change the arguments of the concat function accordingly and
3) what else?

(I do not quite understand what these statements in your code do:

<xsl:apply-templates select="followi ng-sibling::node()[1]"/> and
<xsl:apply-templates
select="followi ng-sibling::*[2]/following-sibling::node()[1]"/>)

Thanks again...

Sep 7 '05 #4

<Be********@gma il.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Thanks, Dimitre, this is very, very helpful!
Just one more question: if the sequence pattern I want to replace
consists of, (e.g.) five elements (and not three like in the example),
I would
1) change the match-value of the last template accordingly and
2) change the arguments of the concat function accordingly and
3) what else?
Change:
<xsl:apply-templates
select="followi ng-sibling::*[2]/following-sibling::node()[1]"/>

to

<xsl:apply-templates
select="followi ng-sibling::*[4]/following-sibling::node()[1]"/>


(I do not quite understand what these statements in your code do:

<xsl:apply-templates select="followi ng-sibling::node()[1]"/>

Apply the templates but not to all children of the current node -- just to
its immediate following sibling
and
<xsl:apply-templates
select="followi ng-sibling::*[2]/following-sibling::node()[1]"/>)

Continue to apply templates sequentially, but skipping the three elements
that we processed in the current template, therefore restarting at the
immediate following sibling of the last element we processed in the current
template.
Cheers,
Dimitre Novatchev.
Sep 7 '05 #5
Hi again,

I've been working succesfully with this "Tree Visiting pattern" for a
week now. Yesterday, however, I added Stylesheet assignments, i.e.
things like

<?xml-stylesheet href="file:../../../2HTML.xsl" type="text/xsl"?>

to my XML documents.

When I now apply the pattern, it does what it is supposed to do, but,
on top of this, duplicates the entire document (leading to
non-well-formed XML because there are two root elements). What's even
stranger: when I add a comment before the root element on top of the
XSL assignment, the output triples the input. I know how to avoid this
(take out the XSL assignments etc.), but I'd like to understand it.
What on earth is going on here?

Kind regards,

Thomas

Sep 19 '05 #6

"Be********@gma il.com" <Be********@goo glemail.com> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.com...
Hi again,

I've been working succesfully with this "Tree Visiting pattern" for a
week now. Yesterday, however, I added Stylesheet assignments, i.e.
things like

<?xml-stylesheet href="file:../../../2HTML.xsl" type="text/xsl"?>

to my XML documents.

When I now apply the pattern, it does what it is supposed to do, but,
on top of this, duplicates the entire document (leading to
non-well-formed XML because there are two root elements). What's even
stranger: when I add a comment before the root element on top of the
XSL assignment, the output triples the input. I know how to avoid this
(take out the XSL assignments etc.), but I'd like to understand it.
What on earth is going on here?

As you haven't provided any code, the reason is probably the bad weather...
:o)

Cheers,
Dimitre Novatchev.
Sep 20 '05 #7
> As you haven't provided any code, the reason is probably the bad weather...
:o)

Cheers,
Dimitre Novatchev.


The weather actually couldn't have been any better ;-) The strange
things happen with *every* variant of the TreeVisitor pattern, for
instance:

1) XSL-File

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:styleshe et version="1.0"
xmlns:xsl="http ://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="no "/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="node()[1]"/>
</xsl:copy>
<xsl:apply-templates select="followi ng-sibling::node()[1]"/>
</xsl:template>
</xsl:stylesheet>

2) XML input

<?xml version="1.0" encoding="UTF-8"?>
<!-- any old comment -->
<x>
<y>
<w>le</w>
</y>
</x>

3) XML output

<?xml version="1.0" encoding="UTF-8"?><!-- any old comment --><x>
<y>
<w>le</w>
</y>
</x><x>
<y>
<w>le</w>
</y>
</x>

In this example, I did the transformation with whatever is built into
the EditiX editor. But the same phenomenon occurs when I use JDOM to do
my transformations .

Thanks for your help,

Thomas

Sep 20 '05 #8
Yes. there was a subtle bug in my code.

The solution is to replace:

<xsl:template match="@* | node()">

with:

<xsl:template match="/ | @* | node()">
What's happening?

Someone (like me) would think that the node test:

node()

matches the root node (document node in XPath 2.0 lingo).

And yes, this *is* true in XPath.

And no, this *isn't true* for a match pattern.

Because a match pattern matches something when the match pattern is
evaluated from its parent, then

node()

will not match the document node "/", because the document node has no
parent by definition.

Because the document node is not matched by any template in our code, the
default template rule is used:
<xsl:template match="*|/">
<xsl:apply-templates/>
</xsl:template>

The xsl:apply-templates instruction causes templates to be applied to *both*
children of the document node (the comment node and the element node), which
produces two almost identical sequences (one including the comment, the
other not) and thus we have every node repeated in the output, with the
exception of the comment node.
Cheers,
Dimitre Novatchev.
Cheers,
Dimitre Novatchev.


"Be********@gma il.com" <Be********@goo glemail.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
As you haven't provided any code, the reason is probably the bad
weather...
:o)

Cheers,
Dimitre Novatchev.


The weather actually couldn't have been any better ;-) The strange
things happen with *every* variant of the TreeVisitor pattern, for
instance:

1) XSL-File

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:styleshe et version="1.0"
xmlns:xsl="http ://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="no "/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="node()[1]"/>
</xsl:copy>
<xsl:apply-templates select="followi ng-sibling::node()[1]"/>
</xsl:template>
</xsl:stylesheet>

2) XML input

<?xml version="1.0" encoding="UTF-8"?>
<!-- any old comment -->
<x>
<y>
<w>le</w>
</y>
</x>

3) XML output

<?xml version="1.0" encoding="UTF-8"?><!-- any old comment --><x>
<y>
<w>le</w>
</y>
</x><x>
<y>
<w>le</w>
</y>
</x>

In this example, I did the transformation with whatever is built into
the EditiX editor. But the same phenomenon occurs when I use JDOM to do
my transformations .

Thanks for your help,

Thomas

Sep 21 '05 #9
Got it, changed it, it did the trick.

Thank you so much,

Thomas

Sep 21 '05 #10

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

Similar topics

5
2439
by: Minho Chae | last post by:
Hello, python lovers!! I'm trying to create combinations of sequences. For example, if the sequence is 'acgt' and the length is 8, then I would like to have 4^8 results such as 'aaaaaaaa', 'aaaaaaac', 'aaaaaaag', 'aaaaaaat', ... 'tttttttt' Is there an easy way doing this?
5
39664
by: mp | last post by:
when I write this in c# : strFileToLoad = strFileToLoad.Substring(0, 2) + strFileToLoad.Substring(2).Replace("\\", "\"); it doesnt like the last "\", and I want to replace \\ with \ what should I do? Thanks
14
3287
by: Etu | last post by:
Hi, I have a string: string c = "'abc' \"cde\", 'mno' \"xyz\","; how can I use the c.Replace(???, ???) method to have this string: "'abc' "cde", 'mno' "xyz"," that is, all the backslashes are removed.
6
8893
by: Chris Anderson | last post by:
Anyone know of a fix (ideally) or an easy workaround to the problem of escape characters not working in regex replacement text? They just come out as literal text For example, you'd think that thi Regex.Replace("<stuff>text</stuff>", "<stuff>", "<stuff>\n" would give yo <stuff text</stuff
8
16125
by: Guy | last post by:
Hi, I'm trying to run this code : strFileContentsHTML.Replace(vbLf, "<br>") strFileContentsHTML.Replace(vbCrLf, "<br>") strFileContentsHTML.Replace(vbCr, "<br>") It doesn't replace newline characters with <br>.
4
4384
by: jgabbai | last post by:
Hi, What is the best way to white list a set of allowable characters using regex or replace? I understand it is safer to whitelist than to blacklist, but am not sure how to go about it. Many thanks!
15
1918
by: =?Utf-8?B?TWlrZSAiWU9fQkVFIiBC?= | last post by:
I have a text file that contains about 8 to 10 text sequences that I need to replace. I want to search and replace all 8 to 10 text sequence anytime I run this script Here is what I have so far. Const ForReading = 1 Const ForWriting = 2
3
4836
by: bstjean | last post by:
Hi everyone, I am trying to find an efficient way to perform a special query. Let me explain what I want. Let's say we are looking for all description that match "this is the target". In fact, I want to find records that match those 4 words in this sequence disregarding the number of spaces (I mean spaces, tabs, Cr, Lf, etc) between them.
1
3399
by: neovantage | last post by:
Hey all, I am using a PHP script which creates headings at run time in a sense at page execution. I am stuck a with a very little problem which i am sure i will have the solution from experts. The problem is when it creates transparent PNG format image then and it pixel ate the image. e.g. If i am using a gradient in background then it vary in color range. Now when i used that php script it generates image successfully but it pixel ate...
0
9768
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
11083
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...
1
10808
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
9549
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
7104
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();...
0
5971
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4592
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
4191
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3215
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.