Просто имел подобную проблему, кроме мне был нужен NodeList и не Документ, вот то, что я придумал. Это - главным образом то же решение как прежде, увеличенный для снижения корневого элемента как NodeList и предложения erickson's использования использования InputSource вместо этого для проблем кодировки символов.
private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);
public static Document loadXMLFrom(String xml) throws Exception {
InputSource is= new InputSource(new StringReader(xml));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
return doc;
}
To expand on the bottom of danivo's answer:
If you want to order by the time they are added to this list then I recommend that instead of using a has_and_belongs_to_many
you actually use a has_many :through
:
game.rb
has_many :played_games
has_many :users, :through => :played_games, :order => "played_games.created_at ASC"
user.rb
has_many :played_games
has_many :games, :through => :played_games
played_game.rb
belongs_to :game
belongs_to :user
Of course, changes pending on the names...
In the played_games table if you have a column called created_at
the second has_many
in games will order by this field and return the users in the order of which they were added to the game.
Я не уверен, но я бы сказал, что порядок гарантированно будет таким же, как ваша база данных гарантирует порядок набора результатов без предложения order by.
Вы можете добавьте : order => "last_name, first_name asc"
в оператор связи : has_and_belongs_to_many
. Это установит поведение по умолчанию для порядка возвращаемых элементов.
Вы также можете сделать @ game.users.find (: all,: order => "last_name, first_name asc")
или создайте именованные области для общего заказа, которые вам понадобятся. Подробности см. В API.
Если действительно важно знать порядок, в котором они были добавлены, вы, вероятно, захотите переключиться на связь has_many: через
, чтобы объединенная таблица имела объект своего своя.