开发者

Add an attribute or create a new level in the XML hierarchy?

开发者 https://www.devze.com 2023-02-14 22:26 出处:网络
I am currently working on an XML document that was written for an XML hierarchywith only 2 levels. Right now, I want to add a one-to-many categorization to it that would break most of the code that wo

I am currently working on an XML document that was written for an XML hierarchy with only 2 levels. Right now, I want to add a one-to-many categorization to it that would break most of the code that works with that file.

I could either add that categorization as a new level, or I can implement it as a attribute on the same level (almost like tagging).

current:

<category>
    <subcategory></subcategory>
<category>

proposed:

<supercategory>
    <category>
        <subcategory></subcategory>
    </category>
</supercategory>

or:

<category supercategory="">
    <subcategory></subcategory>
</category>

Which metho开发者_如何学JAVAd is more maintainable?


To me, one of the strengths of XML is that the hierarchical nature of XML elements is ideally suited to describing hierarchical arrangements of objects, such as in your case. As such, I tend to prefer your first option, as your XML structure more resembles the structure of your data. This makes it much easier to read, manage and understand, IMHO.

That said, only you can really say if the extra effort required to make it work with your existing codebase is worth it. There's certainly nothing stopping doing it your second way if you think the required modifications are too difficult/time consuming, I just don't think it is as elegant a solution.


I think creating a new level is the better solution. It follows the current approach you have (nested elements), which is good, and your first example also has the benefit that the original Category elements itself remains unchanged.

You could also consider a recursive definition. This may be a greater refactoring to consider now, but might avoid a future impact. Your categories were 2-levels, now they're 3, what if you moved to 4 and you need to add a SuperDuperCategory?

This notation could be an alternative:

<category>
    <category>
        <category></category>
    </category>
</category>
0

精彩评论

暂无评论...
验证码 换一张
取 消