Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nokogiri does not honor leading whitespace in some cases #319

Closed
mratzloff opened this issue Jul 28, 2010 · 4 comments
Closed

Nokogiri does not honor leading whitespace in some cases #319

mratzloff opened this issue Jul 28, 2010 · 4 comments

Comments

@mratzloff
Copy link

Look at this weirdness!

require 'nokogiri'
include Nokogiri::XML

document = Document.new
document.root = Node.new('root', document)

foo = Node.new('foo', document)
foo.content = 'foo'
document.root << foo

foo << ' bar' # Notice the leading space

puts document.root

And this is the output:

<root>
  <foo>foobar</foo>
</root>

But it should be this instead, right?

<root>
  <foo>foo bar</foo>
</root>

Maybe you don't consider this a bug for some reason. If not, it would be nice to at least have the ability to set something like :preserve_whitespace => true on the parent node, or pass it in an options hash to Node#add_child() or something.

This is Nokogiri 1.5.0.beta.1 (gem), by the way.

Thanks!

@mratzloff
Copy link
Author

Also, perhaps you'll say to just do this instead:

foo.content += ' bar'

That's fine, but what about this:

require 'nokogiri'
include Nokogiri::XML

document = Document.new
document.root = Node.new('root', document)

foo = Node.new('foo', document)
foo.content = 'foo'
document.root << foo

bar = Node.new('bar', document)
bar.content = 'bar'
foo << bar

foo << ' baz' # Notice the leading space

puts document.root

Results in this:

<root>
  <foo>foo<bar>bar</bar>baz</foo>
</root>

Can't do Node#content() there, and anyway it gets complicated.

@flavorjones
Copy link
Member

The root of this issue is that we strip the tags before creating a DocumentFragment (which is then inserted into the document in the right place).

This stripping is done largely for historical reasons at this point. DocumentFragments used to be a niche use case, but have since become the core of nearly every node-creation API call, and so maybe we should revisit this convention for 1.5.

@mratzloff
Copy link
Author

Yeah, currently the only workaround I've found is to set it twice. It's pretty goofy.

foo = "\nfoo"
node << foo
node.children.last.content = foo

Because naturally each way of setting content works differently. ;-)

@flavorjones
Copy link
Member

{XML,HTML}::DocumentFragment.{new,parse} no longer strip leading and trailing whitespace. Closed by bbebdcc.

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants