Skip to content

Commit

Permalink
XML: allow adding/changing an attribute's value. Fixes #4562
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Jun 13, 2017
1 parent 68b1e62 commit 526837e
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
21 changes: 21 additions & 0 deletions spec/std/xml/xml_spec.cr
Expand Up @@ -315,4 +315,25 @@ describe XML do
str.should eq("< & >")
end
end

it "sets an attribute" do
doc = XML.parse(%{<foo />})
root = doc.root.not_nil!

root["bar"] = "baz"
root["bar"].should eq("baz")
root.to_s.should eq(%{<foo bar="baz"/>})
end

it "changes an attribute" do
doc = XML.parse(%{<foo bar="baz"></foo>})
root = doc.root.not_nil!

root["bar"] = "baz"
root["bar"].should eq("baz")
root.to_s.should eq(%{<foo bar="baz"/>})

root["bar"] = 1
root["bar"].should eq("1")
end
end
5 changes: 5 additions & 0 deletions src/xml/attributes.cr
Expand Up @@ -37,6 +37,11 @@ struct XML::Attributes
find { |node| node.name == name }
end

def []=(name : String, value)
LibXML.xmlSetProp(@node, name, value.to_s)
value
end

def each : Nil
return unless @node.element?

Expand Down
2 changes: 2 additions & 0 deletions src/xml/libxml2.cr
Expand Up @@ -292,6 +292,8 @@ lib LibXML
fun xmlSetGenericErrorFunc(ctx : Void*, f : GenericErrorFunc)

fun xmlGetNsList(doc : Doc*, node : Node*) : NS**

fun xmlSetProp(node : Node*, name : UInt8*, value : UInt8*) : Attr*
end

LibXML.xmlGcMemSetup(
Expand Down
2 changes: 1 addition & 1 deletion src/xml/node.cr
Expand Up @@ -34,7 +34,7 @@ struct XML::Node

# Sets *attribute* of this node to *value*.
# Raises `XML::Error` if this node does not support attributes.
def []=(name : String, value : String)
def []=(name : String, value)
raise XML::Error.new("Can't set attribute of #{type}", 0) unless element?
attributes[name] = value
end
Expand Down

0 comments on commit 526837e

Please sign in to comment.