Hello everyone,
I've recently been charged with the task of manipulating
some XHTML (XML compliant HTML). I've gotten a hang of
changing certain fields with the attr function, but I'm
having trouble inserting new fields into the existing
tree.
For example, lets say my XHTML looks like this:
<html>
<body>
What is Foo?
</body>
</html>
Now let's say I wanted to do two things. One is to insert a
form tag which would make anything that is currently the
child of 'body', to be a child of 'form' and make 'form' a
child of 'body'. This can be done like this:
my $xml = XML::Twig->new(
twig_roots => {
'body' => \&insert_form_tags,
},
);
$xml->parsefile('index.html');
$xml->print;
sub insert_form_tags() {
my ($t, $body) = @_;
$body->insert(
form => {
method => "Post",
action => "submit.cgi"
},
);
}
The outputted XHTML will have the form tags inserted.
<html>
<body>
<form method="Post" action="submit.cgi">
What is Foo?
</form>
</body>
</html>
However, the
other thing I'd like to do is insert a
stand alone field. Something with no children. In the case
of this example, insert a form field <input type="text" />
right after form. Notice the ending / in the tag. (So the
text 'What is Foo?' is not a child of the input tag.
I'd like my html to look like this:
<html>
<body>
<form method="Post" action="submit.cgi">
<input type="text" name="foo_is" />
What is Foo?
</form>
</body>
</html>
Can someone help me with the code to do this? I've looked at
much XML::Twig documentation but haven't found any examples
of people needing to do this (although I'm sure it's a
common practice).
All help greatly appreciated.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.