반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발꿈나무

[Blazor] 버튼 클릭할 경우 XML 파일 열기(4) - XML data 읽어와 browser에 뿌리기 본문

C#/Blazor

[Blazor] 버튼 클릭할 경우 XML 파일 열기(4) - XML data 읽어와 browser에 뿌리기

HYOKYE0NG 2021. 10. 14. 11:10
반응형

 

 

[Blazor] 버튼 클릭할 경우 XML 파일 열기(3) - XML 파일 data 읽기

[Blazor] 버튼 클릭할 경우 XML 파일 열기(2) - 메모장으로 열기 [Blazor] 버튼 클릭할 경우 XML 파일 열기(1) 버튼을 클릭하면 어떤 경로에 있는 xml 파일을 열어보자 우선 나는 Blazor로 프로젝트를 진행중

hyokye0ng.tistory.com

 

 

[Blazor] JSRuntime - 새로운 탭에서 razor 파일 열기

Blazor에서 페이지 이동은 NavManager를 사용한다. NavManager의 NavigateTo 메소드를 사용하면 원하는 페이지로 이동할 수 있다. 아래의 코드는 dcn_no라는 데이터를 파라미터로 해서 dcnlist/dcn_no 페이지로

hyokye0ng.tistory.com

 

이전 포스팅에서 xml 파일을 읽어 콘솔에 데이터를 뿌려보았다.

이번 포스팅에서는 xml 데이터를 웹 브라우저에 뿌려보도록 하자.

 

버튼을 클릭하면 새로운 탭이 열리고 그 탭에 xml 데이터를 뿌릴 것이다.

Blazor에서 새로운 탭을 여는 방법도 포스팅해두었으니 참고하면 된다.

 

 

XML data를 가져오는 방법은 이전 포스팅과 동일하다.

@code{
	[Parameter]
    public string dcn_no { get; set; }
    
    public string xmlrepositoryString { get; set; }
    public XmlDocument xml_doc { get; set; }
    
    private void XML_Load(string dcn_no)
    {
        xmlrepositoryString = SysinfoService.GetXMLRepository();
        string xml_path = @$"{xmlrepositoryString}\{dcn_no}.xml";

        if (File.Exists(xml_path))
        {
            xml_doc = new XmlDocument();
            using (var reader = new StreamReader(xml_path, Encoding.Unicode))
            {
                xml_doc.Load(reader);
                xml_doc.Save(Console.Out);
            }
        }
        else
        {
            Console.WriteLine("The file {0}.xml could not be located", dcn_no);
        }

    }
}

기존의 코드에서는 XML data를 콘솔에 뿌렸지만 이번 포스팅에서는 browser에 뿌릴 것이다.

따라서 xml_doc.Save(Console.Out)을 지우고 string 객체에 xml_doc.InnerXml을 할당하여

html 부분에서 화면에 뿌려준다.

 

<div>
    @if(xml_str != null)
    {
        @xml_str
    }
</div>

@code {
    [Parameter]
    public string dcn_no { get; set; }

    public string xmlrepositoryString { get; set; }
    public XmlDocument xml_doc { get; set; }
    public string xml_str { get; set; }

    protected override void OnInitialized()
    {
        XML_Load(dcn_no);
    }

    private void XML_Load(string dcn_no)
    {
        xmlrepositoryString = SysinfoService.GetXMLRepository();
        string xml_path = @$"{xmlrepositoryString}\{dcn_no}.xml";

        if (File.Exists(xml_path))
        {
            xml_doc = new XmlDocument();
            using (var reader = new StreamReader(xml_path, Encoding.Unicode))
            {
                xml_doc.Load(reader);
                xml_str = xml_doc.InnerXml;
            }
        }
        else
        {
            Console.WriteLine("The file {0}.xml could not be located", dcn_no);
        }

    }

이렇게 하면 browser에 출력이 되지만 다음과 같이 한 줄의 string으로 출력된다.

xml이 이렇게 출력되면 가독성이 너무 떨어지기 때문에

PrettyPrint라는 함수를 추가하여 줄바꿈과 들여쓰기를 포함한 XML 형식의 string으로 변환해준다.

 

 

public static string PrettyPrint(string XML)
    {
        string Result = "";
        MemoryStream MS = new MemoryStream();
        XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
        XmlDocument D = new XmlDocument();

        try
        {
            D.LoadXml(XML);
            W.Formatting = System.Xml.Formatting.Indented;
            D.WriteContentTo(W);
            W.Flush();
            MS.Flush();
            MS.Position = 0;

            StreamReader SR = new StreamReader(MS);
            string FormattedXML = SR.ReadToEnd();

            Result = FormattedXML;
        }
        catch (XmlException)
        {
        }

        MS.Close();
        W.Close();

        return Result;
    }

xml_doc.InnerXML가 PrettyPrint 함수를 거치면 XML형식으로

줄바꿈과 들여쓰기까지 되어서 나온다.

 

PrettyPrint 함수까지 적용한 최종코드와 실행화면은 다음과 같다.

아, 참고로 div에 style="white-space:pre"를 적용해주지 않으면 줄바꿈과 들여쓰기가 인식되지 않는다.

따라서 style을 꼭 추가해주어야 한다.

@page "/dcnlist/xml/{dcn_no}"

@using System.Xml
@using System.IO
@using System.Text
@inject SysinfoService SysinfoService

<h3>XML Contents</h3>

<div style="white-space:pre">
    @if(xml_str != null)
    {
        @xml_str
    }
</div>

@code {
    [Parameter]
    public string dcn_no { get; set; }

    public string xmlrepositoryString { get; set; }
    public XmlDocument xml_doc { get; set; }
    public string xml_str { get; set; }

    protected override void OnInitialized()
    {
        XML_Load(dcn_no);
    }

    private void XML_Load(string dcn_no)
    {
        xmlrepositoryString = SysinfoService.GetXMLRepository();
        string xml_path = @$"{xmlrepositoryString}\{dcn_no}.xml";

        if (File.Exists(xml_path))
        {
            xml_doc = new XmlDocument();
            using (var reader = new StreamReader(xml_path, Encoding.Unicode))
            {
                xml_doc.Load(reader);
                xml_str = PrettyPrint(xml_doc.InnerXml);
            }
        }
        else
        {
            Console.WriteLine("The file {0}.xml could not be located", dcn_no);
        }

    }

    public static string PrettyPrint(string XML)
    {
        string Result = "";
        MemoryStream MS = new MemoryStream();
        XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
        XmlDocument D = new XmlDocument();

        try
        {
            D.LoadXml(XML);
            W.Formatting = System.Xml.Formatting.Indented;
            D.WriteContentTo(W);
            W.Flush();
            MS.Flush();
            MS.Position = 0;

            StreamReader SR = new StreamReader(MS);
            string FormattedXML = SR.ReadToEnd();

            Result = FormattedXML;
        }
        catch (XmlException)
        {
        }

        MS.Close();
        W.Close();

        return Result;
    }
}

 

반응형
Comments