IT박스

XML 속성과 요소

itboxs 2020. 11. 2. 07:45
반응형

XML 속성과 요소


이 질문에 이미 답변이 있습니다.

언제 XML 속성을 사용해야하며 언제 XML 요소를 사용해야합니까?

예 :

<customData>
  <records>
    <record name="foo" description="bar" />
  </records>
</customData>

또는

<customData>
  <records>
    <record>
      <name>foo</name>
      <description>bar</description>
    </record>
  </records>
</customData>

IBM 웹 사이트에는 " XML 디자인의 원리 : 요소와 속성을 사용할 때 "라는 제목의 기사 가 있습니다.

어렵고 빠른 규칙은 많지 않지만 게시물에 언급 된 몇 가지 좋은 지침이 있습니다. 예를 들어 권장 사항 중 하나는 XML 프로세서가 속성 내의 데이터를 정규화하여 원시 텍스트를 수정할 수 있으므로 데이터를 공백에 대해 정규화해서는 안되는 경우 요소를 사용하는 것입니다.

다양한 XML 구조를 개발하면서이 기사를 수시로 참조하고 있습니다. 바라건대 이것은 다른 사람들에게도 도움이 될 것입니다.

편집-사이트에서 :

핵심 콘텐츠의 원리

문제의 정보가 XML로 표현되거나 전달되는 필수 자료의 일부라고 생각하는 경우 요소에 넣으십시오. 사람이 읽을 수있는 문서의 경우 이는 일반적으로 독자에게 전달되는 핵심 콘텐츠를 의미합니다. 기계 지향 레코드 형식의 경우 이는 일반적으로 문제 도메인에서 직접 가져온 데이터를 의미합니다. 정보가 주 통신에 주변 적이거나 부수적이라고 생각하거나 순전히 응용 프로그램이 주 통신을 처리하는 데 도움이되도록 의도 된 경우 속성을 사용하십시오. 이렇게하면 보조 재료로 핵심 콘텐츠가 복잡 해지는 것을 방지 할 수 있습니다. 기계 지향 레코드 형식의 경우 일반적으로 문제 영역의 기본 데이터에 대한 응용 프로그램 별 표기법을 의미합니다.

예를 들어, 문서 제목이 속성에 배치 된 대부분의 XML 형식을 보았습니다. 일반적으로 기업에서 자체 개발했습니다. 제목은 항상 요소 콘텐츠에 있어야하는 문서 커뮤니케이션의 기본 부분이라고 생각합니다. 다른 한편으로, 나는 종종 내부 제품 식별자가 제품의 설명 레코드에 요소로 던져지는 경우를 보았습니다. 이러한 경우 중 일부에서는 특정 내부 제품 코드가 문서의 대부분의 독자 나 프로세서에게 주요 관심사가 아니기 때문에 속성이 더 적절했습니다. 특히 ID가 매우 길거나 알 수없는 형식 인 경우에는 더욱 그렇습니다.

기본 데이터가 요소로, 메타 데이터가 속성으로 들어간다고 들었을 것입니다. 위의 두 단락은 실제로 동일한 원칙을 표현하지만 더 신중하고 덜 모호한 언어로 표현됩니다.

구조화 된 정보의 원리

정보가 구조화 된 형식으로 표현되는 경우, 특히 구조가 확장 가능한 경우 요소를 사용하십시오. 반면에 정보가 원자 토큰으로 표현되는 경우 속성을 사용하십시오. 요소는 XML로 구조를 표현하기위한 확장 가능한 엔진입니다. 거의 모든 XML 처리 도구는이 사실을 중심으로 설계되었으며, 구조화 된 정보를 요소로 적절하게 분해하면 처리 도구가 설계를 보완하고 그에 따라 생산성과 유지 보수성을 확보 할 수 있습니다. 속성은 요소에 표현 된 정보의 단순한 속성을 표현하기 위해 설계되었습니다. 구조화 된 정보를 속성으로 구분하여 XML의 기본 아키텍처에 대해 작업하는 경우 약간의 간결함과 편리함을 얻을 수 있지만 유지 관리 비용을 지불하게됩니다.

날짜가 좋은 예입니다. 날짜는 구조가 고정되어 있고 일반적으로 단일 토큰으로 작동하므로 속성으로 의미가 있습니다 (가급적이면 ISO-8601로 표현됨). 반면에 개인 이름을 나타내는 것은 디자이너를 놀라게하는이 원칙을 본 경우입니다. 속성에서 이름을 많이 볼 수 있지만 개인 이름은 요소 콘텐츠에 있어야한다고 항상 주장 해 왔습니다. 개인 이름은 놀랍도록 다양한 구조를 가지고 있습니다 (일부 문화에서는 경어를 생략하거나 이름의 일부 순서를 가정하여 혼란이나 불쾌감을 유발할 수 있습니다). 개인 이름은 원자 토큰이 아닙니다. 예를 들어, 때로는 이름과 성으로 검색하거나 정렬 할 수 있습니다. 단일 요소의 내용에 전체 이름을 넣는 것도 속성에 넣는 것만 큼 문제가된다는 점을 지적해야합니다.


더 나은 요소 대 속성 인수 중 하나는 UK GovTalk 지침 에서 비롯됩니다 . 이는 정부 관련 XML 교환에 사용되는 모델링 기술을 정의하지만 그 자체로 장점이 있으며 고려할 가치가 있습니다.

스키마는 요소가 XML 인스턴스에서 정보 콘텐츠의 주요 보유자가되도록 설계되어야합니다. 속성은 요소 콘텐츠에 대한 더 많은 정보를 제공하는 간단한 항목 인 보조 메타 데이터를 보유하는 데 더 적합합니다. 애트리뷰트는 이것이 모호성을 유발할 수있는 다른 애트리뷰트를 규정하는 데 사용되어서는 안됩니다.

요소와 달리 속성은 구조화 된 데이터를 보유 할 수 없습니다. 이러한 이유로 정보 콘텐츠의 주요 보유자로 요소가 선호됩니다. 그러나 속성을 사용하여 요소의 콘텐츠에 대한 메타 데이터를 보유하도록 허용하면 (예 : 날짜 형식, 측정 단위 또는 값 집합 식별) 인스턴스 문서를 더 간단하고 이해하기 쉽게 만들 수 있습니다.

생년월일은 메시지에 다음과 같이 표시 될 수 있습니다.

 <DateOfBirth>1975-06-03</DateOfBirth> 

그러나 생년월일이 확인 된 방법과 같은 추가 정보가 필요할 수 있습니다. 이것은 속성으로 정의되어 메시지의 요소를 다음과 같이 만들 수 있습니다.

<DateOfBirth VerifiedBy="View of Birth Certificate">1975-06-03</DateOfBirth> 

다음은 부적절합니다.

<DateOfBirth VerifiedBy="View of Birth Certificate" ValueSet="ISO 8601" Code="2">1975-06-03</DateOfBirth>   

여기서 코드가 VerifiedBy 또는 ValueSet 속성을 규정하는지 여부는 명확하지 않습니다. 더 적절한 변환은 다음과 같습니다.

 <DateOfBirth>    
   <VerifiedBy Code="2">View of Birth Certificate</VerifiedBy>     
   <Value ValueSet="ISO 8601">1975-06-03</Value>
 </DateOfBirth>

개인적으로 저는 단순한 단일 값 속성에 속성을 사용하는 것을 좋아합니다. 요소는 (분명히) 복잡한 유형이나 반복되는 값에 더 적합합니다.

단일 값 속성의 경우 특성은 대부분의 API에서 더 간결한 XML과 더 간단한 주소 지정으로 이어집니다.


그것은 주로 선호도의 문제입니다. 나는 이것이 대안보다 더 간결하다고 생각하기 때문에 가능한 경우 그룹화에 요소를 사용하고 데이터에 속성을 사용합니다.

예를 들어 선호합니다 .....

<?xml version="1.0" encoding="utf-8"?>
<data>
    <people>
        <person name="Rory" surname="Becker" age="30" />
        <person name="Travis" surname="Illig" age="32" />
        <person name="Scott" surname="Hanselman" age="34" />
    </people>
</data>

...대신에....

<?xml version="1.0" encoding="utf-8"?>
<data>
    <people>
        <person>
            <name>Rory</name>
            <surname>Becker</surname>
            <age>30</age>
        </person>
        <person>
            <name>Travis</name>
            <surname>Illig</surname>
            <age>32</age>
        </person>
        <person>
            <name>Scott</name>
            <surname>Hanselman</surname>
            <age>34</age>
        </person>
    </people>
</data>

그러나 20-30 자 이내로 쉽게 표현되지 않거나 이스케이프가 필요한 많은 따옴표 또는 기타 문자를 포함하는 데이터가있는 경우 요소를 분리 할 때입니다. 아마도 CData 블록으로 가능합니다.

<?xml version="1.0" encoding="utf-8"?>
<data>
    <people>
        <person name="Rory" surname="Becker" age="30" >
            <comment>A programmer whose interested in all sorts of misc stuff. His Blog can be found at http://rorybecker.blogspot.com and he's on twitter as @RoryBecker</comment>
        </person>
        <person name="Travis" surname="Illig" age="32" >
            <comment>A cool guy for who has helped me out with all sorts of SVn information</comment>
        </person>
        <person name="Scott" surname="Hanselman" age="34" >
            <comment>Scott works for MS and has a great podcast available at http://www.hanselminutes.com </comment>
        </person>
    </people>
</data>

As a general rule, I avoid attributes altogether. Yes, attributes are more compact, but elements are more flexible, and flexibility is one of the most important advantages of using a data format like XML. What is a single value today can become a list of values tomorrow.

Also, if everything's an element, you never have to remember how you modeled any particular bit of information. Not using attributes means you have one less thing to think about.


Check out Elements vs. attributes by Ned Batchelder.

Nice explanation and a good list of the benefits and disadvantages of Elements and Attributes.

He boils it down to:

Recommendation: Use elements for data that will be produced or consumed by a business application, and attributes for metadata.

Important: Please see @maryisdead's comment below for further clarification.


The limitations on attributes tell you where you can and can't use them: the attribute names must be unique, their order cannot be significant, and both the name and the value can contain only text. Elements, by contrast, can have non-unique names, have significant ordering, and can have mixed content.

Attributes are usable in domains where they map onto data structures that follow those rules: the names and values of properties on an object, of columns in a row of a table, of entries in a dictionary. (But not if the properties aren't all value types, or the entries in the dictionary aren't strings.)


My personal rule of thumb: if an element can contain only one of that thing, and its an atomic data (id, name, age, type, etc...) it should be an attribute otherwise an element.


I tend to use elements when it's data that a human reader would need to know and attributes when it's only for processing (e.g. IDs). This means that I rarely use attributes, as the majority of the data is relevant to the domain being modeled.


Here is another strategy that can help distinguishing elements from attributes: think of objects and keep in mind MVC.

Objects can have members (object variables) and properties (members with setters and getters). Properties are highly useful with MVC design, allowing change notification mechanism.

If this is the direction taken, attributes will be used for internal application data that cannot be changed by the user; classic examples will be ID or DATE_MODIFIED. Elements will therefore be used to data that can be modified by users.

So the following would make sense considering the librarian first add a book item (or a magazine), and then can edit its name author ISBN etc:

<?xml version="1.0" encoding="utf-8"?>
<item id="69" type="book">
    <authors count="1">
        <author>
            <name>John Smith</name>
        <author>
    </authors>
    <ISBN>123456790</ISBN>
</item>

참고URL : https://stackoverflow.com/questions/152313/xml-attributes-vs-elements

반응형