XML에서 요소 또는 속성을 사용해야합니까?
이 질문에 이미 답변이 있습니다.
- XML 속성 대 XML 요소 20 답변
W3Schools에서 XML 속성 에 대해 배우고 있습니다.
저자는 다음을 언급합니다 (내 강조).
XML 요소와 속성
<person sex="female"> <firstname>Anna</firstname> <lastname>Smith</lastname> </person>
<person> <sex>female</sex> <firstname>Anna</firstname> <lastname>Smith</lastname> </person>
첫 번째 예에서 섹스는 속성입니다. 마지막으로 섹스는 요소입니다. 두 예 모두 동일한 정보를 제공합니다.
속성을 사용하는시기와 요소를 사용하는시기에 대한 규칙은 없습니다. 속성은 HTML에서 편리합니다. XML에서 내 조언은 그것들을 피하는 것입니다. 대신 요소를 사용하십시오.
XML 속성을 사용하지 않습니까?
속성 사용과 관련된 몇 가지 문제는 다음과 같습니다.
- 속성은 여러 값을 포함 할 수 없습니다 (요소는 가능).
- 속성은 트리 구조를 포함 할 수 없습니다 (요소는 가능).
- 속성은 쉽게 확장 할 수 없습니다 (향후 변경을 위해).
속성은 읽고 유지하기가 어렵습니다. 데이터에 요소를 사용하십시오. 데이터와 관련이없는 정보에는 속성을 사용하십시오.
저자의 견해는 유명한 것입니까, 아니면 이것이 XML의 모범 사례입니까?
XML의 속성은 피해야합니까?
W3Schools는 또한 다음과 같이 언급했습니다 (내 강조).
메타 데이터에 대한 XML 속성
때때로 ID 참조가 요소에 할당됩니다. 이러한 ID는 HTML의 ID 속성과 거의 동일한 방식으로 XML 요소를 식별하는 데 사용할 수 있습니다. 이 예는이를 보여줍니다.
<messages> <note id="501"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> <note id="502"> <to>Jani</to> <from>Tove</from> <heading>Re: Reminder</heading> <body>I will not</body> </note> </messages>
위의 ID는 다른 메모를 식별하기위한 식별자입니다. 메모 자체의 일부가 아닙니다.
여기서 제가 말하려는 것은 메타 데이터 (데이터에 대한 데이터)가 속성으로 저장되어야하고 데이터 자체가 요소로 저장되어야한다는 것입니다.
속성 또는 요소의 사용은 일반적으로 모델링하려는 데이터에 의해 결정됩니다.
특정 법인 인 경우 예를 들어, PART 데이터, 다음은 요소 수 있도록하는 것이 좋습니다. 예를 들어 직원의 이름은 직원 데이터의 필수 부분입니다.
이제 데이터 (데이터에 대한 추가 정보를 제공하는 것)에 대한 METADATA 를 전달하고 싶지만 실제로 데이터의 일부가 아니라면 속성으로 만드는 것이 좋습니다. 예를 들어, 각 직원이 백엔드 처리에 필요한 GUID를 가지고 있다고 가정 해 보겠습니다 (GUID는 XML을 보는 사람에게 정말 유용한 정보를 전달하는 것이 아니라 다른 목적에 필요할 수 있습니다).
무언가가 속성이나 요소 여야한다는 규칙은 없습니다.
어떤 대가를 치르더라도 속성을 피할 필요는 없습니다. 때로는 요소보다 모델링하기가 더 쉽습니다. 실제로 표현하려는 데이터에 따라 다릅니다.
OP 5 년 후 0.02는 정반대입니다. 설명하겠습니다.
- 유사한 데이터와 해당 데이터의 속성을 그룹화 할 때 요소를 사용하십시오.
- 모든 것에 요소를 사용하지 마십시오.
- 데이터가 반복되는 경우 (1 개 이상) 아마도 요소 일 것입니다.
- 데이터가 반복되지 않고 다른 항목과 상호 연관 될 때만 의미가있는 경우 속성입니다.
- 데이터에 다른 속성 (예 : 이름)이 없으면 속성입니다.
- 컬렉션 구문 분석을 지원하기 위해 같은 요소 그룹화 (예 : / xml / character)
- 유사한 요소 이름을 재사용하여 데이터 구문 분석 지원
- 결코, 이제까지 , 위치를 표시하는 요소 이름에 숫자를 사용하지 않습니다. (예 : character1, character2)이 관행은 구문 분석을 매우 어렵게 만듭니다 (# 6 참조, 구문 분석 코드는 단순히 / character가 아닌 / character1, / character2 등이어야합니다.
다른 방법으로 고려 :
- 모든 데이터를 속성 으로 생각하여 시작하십시오 .
- 속성을 요소로 논리적으로 그룹화합니다. 데이터를 알고 있다면 속성을 요소로 변환 할 필요가 거의 없습니다. 요소 (컬렉션 또는 반복 데이터)가 필요한시기를 이미 알고있을 것입니다.
- 논리적으로 요소 그룹화
- 확장해야하는 경우가 발생하면 위의 프로세스에서 논리적 구조를 기반으로 새 요소 / 속성을 추가합니다. 새로운 자식 요소 컬렉션을 추가해도 디자인이 "파손"되지 않으며 시간이 지남에 따라 읽기가 더 쉬워집니다.
예를 들어, 책과 주요 인물의 단순한 컬렉션을 보면 제목에 "어린이"가없는 단순한 요소입니다. 모든 캐릭터에는 이름과 나이가 있습니다.
<book title='Hitchhiker's Guide to the Galaxy' author='Douglas Adams'>
<character name='Zaphod Beeblebrox' age='100'/>
<character name='Arthur Dent' age='42'/>
<character name='Ford Prefect' age='182'/>
</book>
<book title='On the Road' author='Jack Kerouac'>
<character name='Dean Moriarty' age='30'/>
<character name='Old Bull Lee' age='42'/>
<character name='Sal Paradise' age='42'/>
</book>
책에 여러 명의 저자가있을 수 있다고 주장 할 수 있습니다. 좋습니다. 새 작성자 요소를 추가하여 확장하면됩니다 (선택적으로 원래 @author 제거). 물론, 당신은 원래 구조를 깨뜨 렸지만 실제로는 꽤 드물고 해결하기 쉽습니다. 단일 저자를 가정 한 원본 XML의 소비자는 어쨌든 변경해야합니다 (저자는 'book'테이블의 열에서 'author'테이블로 저자를 이동하기 위해 DB를 변경할 가능성이 높습니다).
<book title='Hitchhiker's Guide to the Galaxy'>
<author name='Douglas Adams'/>
<author name='Some Other Guy'/>
<character name='Zaphod Beeblebrox' age='100'/>
<character name='Arthur Dent' age='42'>
<character name='Ford Prefect' age='182'/>
</book>
가장 중요한 것은 속성에 항목을 넣으면 XML이 덜 장황하다는 것입니다.
비교
<person name="John" age="23" sex="m"/>
에 맞서
<person>
<name>
John
</name>
<age>
<years>
23
</years>
</age>
<sex>
m
</sex>
</person>
예, 약간 편향되고 과장되었지만 요점은
정확한 질문을 검색하기 위해 Google을 사용했습니다. 먼저 http://www.ibm.com/developerworks/library/x-eleatt/index.html 이 기사를 읽었습니다 . 하지만 간단한 질문으로는 너무 길었다. 어쨌든 나는이 주제에 대한 모든 답변을 읽었으며 만족스러운 요약을 찾지 못했습니다. 따라서 나는 후자의 기사로 돌아갔다. 요약은 다음과 같습니다.
요소를 언제 사용하고 정보를 제공하기 위해 속성을 언제 사용합니까?
- 문제의 정보 자체가 요소로 마크 업 될 수 있다면 요소에 넣습니다.
- 정보가 속성 양식에 적합하지만 동일한 요소에서 동일한 이름의 여러 속성으로 끝날 수있는 경우 대신 하위 요소를 사용하십시오.
- If the information is required to be in a standard DTD-like attribute type such as ID, IDREF, or ENTITY, use an attribute.
- If the information should not be normalized for white space, use elements. (XML processors normalize attributes in ways that can change the raw text of the attribute value.)
Principle of core content
If you consider the information in question to be part of the essential material that is being expressed or communicated in the XML, put it in an element. If you consider the information to be peripheral or incidental to the main communication, or purely intended to help applications process the main communication, use attributes.
Principle of structured information
If the information is expressed in a structured form, especially if the structure may be extensible, use elements. If the information is expressed as an atomic token, use attributes.
Principle of readability
If the information is intended to be read and understood by a person, use elements. If the information is most readily understood and digested by a machine, use attributes.
Principle of element/attribute binding
Use an element if you need its value to be modified by another attribute. [..] it is almost always a terrible idea to have one attribute modify another.
This is a short summary of the important bits from the article. If you wish to see examples and full description of every case, then refer to the original article.
Attributes model mapping. A set of attributes on an element isomorphizes directly onto a name/value map in which the values are text or any serializable value type. In C#, for instance, any Dictionary<string, string>
object can be represented as an XML attribute list, and vice versa.
This is emphatically not the case with elements. While you can always transform a name/value map into a set of elements, the reverse is not the case, e.g.:
<map>
<key1>value</key1>
<key1>another value</key1>
<key2>a third value</key2>
</map>
If you transform this into a map, you'll lose two things: the multiple values associated with key1
, and the fact that key1
appears before key2
.
The significance of this becomes a lot clearer if you look at DOM code that's used to update information in a format like this. For instance, it's trivial to write this:
foreach (string key in map.Keys)
{
mapElement.SetAttribute(key, map[key]);
}
That code is concise and unambiguous. Contrast it with, say:
foreach (string key in map.Keys)
{
keyElement = mapElement.SelectSingleNode(key);
if (keyElement == null)
{
keyElement = mapElement.OwnerDocument.CreateElement(key);
mapElement.AppendChild(keyElement);
}
keyElement.InnerText = value;
}
You can't put a CDATA in an attribute. In my experience, sooner or later you are going to want to put single quotes, double quotes and/or entire XML documents into a "member", and if it's an attribute you're going to be cursing at the person who used attributes instead of elements.
Note: my experience with XML mainly involved cleaning up other peoples'. These people seemed to follow the old adage "XML is like violence. If using it hasn't solved your problem, then you haven't used enough."
This is an example where attributes are data about data.
Databases are named by their ID attribute.
The "type" attribute of the database denotes what is expected to be found inside the database tag.
<databases>
<database id='human_resources' type='mysql'>
<host>localhost</host>
<user>usrhr</user>
<pass>jobby</pass>
<name>consol_hr</name>
</database>
<database id='products' type='my_bespoke'>
<filename>/home/anthony/products.adb</filename>
</database>
</databases>
It all depends on what XML is used for. When it's mostly interop between software and machines - such as Web services it's easier to go all-elements if only for the sake of consistency (and also some frameworks prefer it that way, e.g. WCF). If it is targeted for human consumption - i.e. primarily created and/or read by people - then judicious use of attributes can improve readability quite a lot; XHTML is a reasonable example of that, and also XSLT and XML Schema.
I usually work on the basis that attributes are metadata - that is, data about the data. One thing I do avoid is putting lists in attributes. e.g.
attribute="1 2 3 7 20"
Otherwise you have an extra level of parsing to extract each element. If XML provides the structure and tools for lists, then why impose another yourself.
One scenario where you may want to code in preference for attributes is for processing speed via a SAX parser. Using a SAX parser you will get an element call back containing the element name and the list of attributes. If you had used multiple elements instead then you'll get multiple callbacks (one for each element). How much of a burden/timesink this is is up for debate of course, but perhaps worth considering.
The author's points are correct (except that attributes may contain a list of values). The question is whether or not you care about his points.
It's up to you.
It's because of that kind of rubbish that you should avoid w3schools. If anything, that's even worse than the appalling stuff they have about JavaScript.
As a general rule, I would suggest that content - that is, data which are expected to be consumed by an end user (whether that be a human reading, or a machine receiving information for processing) - is best contained within an element. Metadata - for example an ID associated with a piece of content but only of value for internal use rather than for display to the end user - should be in an attribute.
Here's another thing to keep in mind when deciding on an XML format: If I recall correctly, the values of "id" attributes must not be all numeric, they must meet the rules for names in XML. And of course the values must be unique. I have a project that must process files that don't meet these requirements (although they are clean XML in other respects), which made processing the files more convoluted.
You could probably see the issue in a semantic way.
If the data is more tight linked with the element it would be an attribute.
i.e: an ID of an element, i would put it as an attribute of the element.
But it's true that while parsing a document attributes could cause more headaches than elements.
All depends on you, and how you design your Schema.
참고URL : https://stackoverflow.com/questions/1096797/should-i-use-elements-or-attributes-in-xml
'Program Tip' 카테고리의 다른 글
NSString containsString 충돌 (0) | 2020.11.01 |
---|---|
C 부동 소수점 리터럴을 double이 아닌 부동 소수점으로 만듭니다. (0) | 2020.11.01 |
한 분기를 다른 분기처럼 만드는 git 명령 (0) | 2020.11.01 |
git 상태 성능을 개선하는 방법 (0) | 2020.11.01 |
JavaScript for-loop를 CoffeeScript로 어떻게 변환 할 수 있습니까? (0) | 2020.11.01 |