다음을 통해 공유


방법: LINQ를 사용하여 XML 변환(Visual Basic)

XML 리터럴을 사용하면 한 원본에서 XML을 쉽게 읽고 새 XML 형식으로 변환할 수 있습니다. LINQ 쿼리를 활용하여 변환할 콘텐츠를 검색하거나 기존 문서의 콘텐츠를 새 XML 형식으로 변경할 수 있습니다.

이 항목의 예제에서는 콘텐츠를 XML 원본 문서에서 HTML로 변환하여 브라우저에서 볼 수 있습니다.

비고

컴퓨터는 다음 지침에서 Visual Studio 사용자 인터페이스 요소 중 일부에 대해 다른 이름 또는 위치를 표시할 수 있습니다. 가지고 있는 Visual Studio 버전과 사용하는 설정에 따라 이러한 요소가 결정됩니다. 자세한 내용은 IDE 개인 설정참조하세요.

XML 문서를 변환하려면

  1. Visual Studio에서 콘솔 애플리케이션 프로젝트 템플릿에 새 Visual Basic 프로젝트를 만듭니다.

  2. 프로젝트에서 만든 Module1.vb 파일을 두 번 클릭하여 Visual Basic 코드를 수정합니다. Sub Main 모듈의 Module1에 다음 코드를 추가합니다. 이 코드는 원본 XML 문서를 개체로 XDocument 만듭니다.

    Dim catalog =
      <?xml version="1.0"?>
        <Catalog>
          <Book id="bk101">
            <Author>Garghentini, Davide</Author>
            <Title>XML Developer's Guide</Title>
            <Price>44.95</Price>
            <Description>
              An in-depth look at creating applications
              with <technology>XML</technology>. For
              <audience>beginners</audience> or
              <audience>advanced</audience> developers.
            </Description>
          </Book>
          <Book id="bk331">
            <Author>Spencer, Phil</Author>
            <Title>Developing Applications with Visual Basic .NET</Title>
            <Price>45.95</Price>
            <Description>
              Get the expert insights, practical code samples,
              and best practices you need
              to advance your expertise with <technology>Visual
              Basic .NET</technology>.
              Learn how to create faster, more reliable applications
              based on professional,
              pragmatic guidance by today's top <audience>developers</audience>.
            </Description>
          </Book>
        </Catalog>
    

    방법: 파일, 문자열 또는 스트림에서 XML 로드

  3. 소스 XML 문서를 만드는 코드 다음에 다음 코드를 추가하여 개체에서 모든 <Book> 요소를 검색하고 HTML 문서로 변환합니다. Book< 요소 목록은 >변환된 HTML을 포함하는 개체 컬렉션을 XElement 반환하는 LINQ 쿼리를 사용하여 만들어집니다. 포함된 식을 사용하여 원본 문서의 값을 새 XML 형식으로 넣을 수 있습니다.

    결과 HTML 문서는 "Save" 메서드를 사용하여 파일에 기록됩니다.

    Dim htmlOutput =
      <html>
        <body>
          <%= From book In catalog.<Catalog>.<Book>
              Select <div>
                       <h1><%= book.<Title>.Value %></h1>
                       <h3><%= "By " & book.<Author>.Value %></h3>
                        <h3><%= "Price = " & book.<Price>.Value %></h3>
                        <h2>Description</h2>
                        <%= TransformDescription(book.<Description>(0)) %>
                        <hr/>
                      </div> %>
        </body>
      </html>
    
    htmlOutput.Save("BookDescription.html")
    
  4. Sub MainModule1에, Sub설명< 노드를 지정된 HTML 형식으로 변환하는 새 메서드(>)를 추가합니다. 이 메서드는 이전 단계의 코드에서 호출되며 Description< 요소의 >형식을 유지하는 데 사용됩니다.

    이 메서드는 Description< 요소의 >하위 요소를 HTML로 바꿉니다. 이 ReplaceWith 메서드는 하위 요소의 위치를 유지하는 데 사용됩니다. Description 요소의 <변환된 콘텐츠는 HTML 단락(>p<) 요소에 포함>됩니다. 이 Nodes 속성은 <Description> 요소의 변환된 콘텐츠를 검색하는 데 사용됩니다. 이렇게 하면 하위 요소가 변환된 콘텐츠에 포함됩니다.

    Sub Main 다음에 Module1 다음 코드를 추가합니다.

    Public Function TransformDescription(ByVal desc As XElement) As XElement
    
      ' Replace <technology> elements with <b>.
      Dim content = (From element In desc...<technology>).ToList()
    
      If content.Count > 0 Then
        For i = 0 To content.Count - 1
          content(i).ReplaceWith(<b><%= content(i).Value %></b>)
        Next
      End If
    
      ' Replace <audience> elements with <i>.
      content = (From element In desc...<audience>).ToList()
    
      If content.Count > 0 Then
        For i = 0 To content.Count - 1
          content(i).ReplaceWith(<i><%= content(i).Value %></i>)
        Next
      End If
    
      ' Return the updated contents of the <Description> element.
      Return <p><%= desc.Nodes %></p>
    End Function
    
  5. 변경 내용을 저장합니다.

  6. F5 키를 눌러 코드를 실행합니다. 결과 저장 문서는 다음과 유사합니다.

    <?xml version="1.0"?>
    <html>
      <body>
        <div>
          <h1>XML Developer's Guide</h1>
          <h3>By Garghentini, Davide</h3>
          <h3>Price = 44.95</h3>
          <h2>Description</h2>
          <p>
            An in-depth look at creating applications
            with <b>XML</b>. For
            <i>beginners</i> or
            <i>advanced</i> developers.
          </p>
          <hr />
        </div>
        <div>
          <h1>Developing Applications with Visual Basic .NET</h1>
          <h3>By Spencer, Phil</h3>
          <h3>Price = 45.95</h3>
          <h2>Description</h2>
          <p>
            Get the expert insights, practical code
            samples, and best practices you need
            to advance your expertise with <b>Visual
            Basic .NET</b>. Learn how to create faster,
            more reliable applications based on
            professional, pragmatic guidance by today's
            top <i>developers</i>.
          </p>
          <hr />
        </div>
      </body>
    </html>
    

참고하십시오