diff --git a/src/xml/xml_native_reader.cc b/src/xml/xml_native_reader.cc index d298148a..390639e7 100644 --- a/src/xml/xml_native_reader.cc +++ b/src/xml/xml_native_reader.cc @@ -4181,32 +4181,31 @@ void mjXReader::Body(XMLElement* section, mjsBody* body, mjsFrame* frame, } mjtObj type = has_body ? mjOBJ_BODY : mjOBJ_FRAME; - mjsElement* child = mjs_findElement(spec, type, (prefix+child_name).c_str()); - mjsFrame* pframe = frame ? frame : mjs_addFrame(body, nullptr); + string full_name = prefix+child_name; + if (mjs_findElement(spec, type, full_name.c_str())) { + throw mjXError(elem, "cannot attach: element %s already exists", full_name.c_str()); + } - if (!child) { - mjSpec* asset = mjs_findSpec(spec, model_name.c_str()); - if (!asset) { - throw mjXError(elem, "could not find model '%s'", model_name.c_str()); - } - if (child_name.empty()) { - child = asset->element; - } else { - child = mjs_findElement(asset, type, child_name.c_str()); - if (!child) { - throw mjXError(elem, "could not find %s", - (string(mju_type2Str(type)) + " '" + child_name + "'").c_str()); - } - } - if (!mjs_attach(pframe->element, child, prefix.c_str(), "")) { - throw mjXError(elem, "%s", stripError(mjs_getError(spec))); - } + mjSpec* asset = mjs_findSpec(spec, model_name.c_str()); + if (!asset) { + throw mjXError(elem, "could not find model '%s'", model_name.c_str()); + } + + mjsElement* child; + if (child_name.empty()) { + child = asset->element; } else { - // only set frame to existing body - if (mjs_setFrame(child, pframe)) { - throw mjXError(elem, "%s", stripError(mjs_getError(spec))); + child = mjs_findElement(asset, type, child_name.c_str()); + if (!child) { + throw mjXError(elem, "could not find %s", + (string(mju_type2Str(type)) + " '" + child_name + "'").c_str()); } } + + mjsFrame* pframe = frame ? frame : mjs_addFrame(body, nullptr); + if (!mjs_attach(pframe->element, child, prefix.c_str(), "")) { + throw mjXError(elem, "%s", stripError(mjs_getError(spec))); + } } // no match diff --git a/test/xml/xml_native_reader_test.cc b/test/xml/xml_native_reader_test.cc index 8d840604..f152c1ab 100644 --- a/test/xml/xml_native_reader_test.cc +++ b/test/xml/xml_native_reader_test.cc @@ -1632,7 +1632,7 @@ TEST_F(XMLReaderTest, RepeatedPrefix) { mjSpec* spec = mj_parseXMLString(parent, vfs.get(), err.data(), err.size()); EXPECT_THAT(spec, IsNull()); - EXPECT_THAT(err.data(), HasSubstr("mismatched parents")); + EXPECT_THAT(err.data(), HasSubstr("cannot attach")); mj_deleteSpec(spec); mj_deleteVFS(vfs.get()); }