2022년 9월 16일 금요일

[C#] XDocument, XmlDocument Convert, Revert

 






public static class DocumentExtensions
{
    public static XmlDocument ToXmlDocument(this XDocument xDocument)
    {
        var xmlDocument = new XmlDocument();
        using (var xmlReader = xDocument.CreateReader())
        {
            xmlDocument.Load(xmlReader);
        }
        return xmlDocument;
    }

    public static XDocument ToXDocument(this XmlDocument xmlDocument)
    {
        using (var nodeReader = new XmlNodeReader(xmlDocument))
        {
            nodeReader.MoveToContent();
            return XDocument.Load(nodeReader);
        }
    }
}

[Error] xml로드할 때 발생하는 에러 string to XML unity

 



//         string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
        if (LobbyMainScene_Xml.StartsWith(_byteOrderMarkUtf8))
        {
            LobbyMainScene_Xml = LobbyMainScene_Xml.Remove(0, _byteOrderMarkUtf8.Length);
        }
        xmlDoc.LoadXml(LobbyMainScene_Xml);





The hidden character is probably BOM. The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.

Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
    xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}

I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object. On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.







2022년 9월 14일 수요일

unity string ConvertTo enum

 


temp.cardGrades[0] = (CardGrade)Enum.Parse(typeof(CardGrade), convertData1[1]);


Unity SearchLogic 개선(List 처리 추가, 중복검색 클래스)

 



인자로 리스트 있을때 처리


///ProductName은 리스트 구조라서 람다식안에서 foreach를 한번 돌려줬다


이렇게 해서 해결


public List<CompanyInfo> SearhCompanyInf(int value, string input, bool sort= true)
    {
        Func<CompanyInfo, bool> condition;
        //Func<CompanyInfo, object> order;
        string search = input.ToLower();

        //if (value < 0 || value >= searchDropdown.options.Count)
        //    return new List<FixtureItemData>();
        switch (value) //Dropdown value에 따라 조건 설정
        {
            case 0: // 제조사
                condition = item => item.CompanyName.ToLower().Contains(search);
                //order = item => item.CompanyName;
                break;
            case 1: // 조명 이름

                ///ProductName은 리스트 구조라서 람다식안에서 foreach를 한번 돌려줬다
                condition = item =>
                {
                    foreach (var x in item.ProductNames)
                    {
                        if (x.Contains(search))
                            return true;
                    }
                    return false;
                };
                //order = item => item.ProductNames;
               
               


                //condition = item => item.FindCompany(search);
                //order = item => item.ProductNames;
                break;
            //case 2: // 채널
            //    condition = item => item.channelList.Count.ToString().Contains(search);
            //    order = item => item.channelList.Count;
            //    break;
            default: //모드
                condition = item => item.CompanyName.ToLower().Contains(search);
                //order = item => item.CompanyName;
                break;
        }

        int i = 1;
        IEnumerable<CompanyInfo> result;

        result = originTable.Where(condition);


        //result = sort ? result.OrderByDescending(order) : result.OrderBy(order);

        result = result.Select(x => new CompanyInfo
        {
            CompanyName = x.CompanyName,
            floorIdx = x.floorIdx,
            ProductNames = x.ProductNames
        });

        return result.ToList();

    }




///중복검색 제거 클래스
public class CompanyUiItem
{
    public string companyName;
    public string companyType;
    public string url;
    public List<string> products;
    public List<string> cars;


    public override bool Equals(object obj)
    {
        return this.companyName == ((CompanyUiItem)obj).companyName &&
            this.companyType == ((CompanyUiItem)obj).companyType &&
            this.cars.SequenceEqual(((CompanyUiItem)obj).cars)&&
            this.products.SequenceEqual(((CompanyUiItem)obj).products)
            ;
    }
    public override int GetHashCode()
    {
        return companyName.GetHashCode() ^ companyType.GetHashCode() ^ cars.GetHashCode()^products.GetHashCode();
    }

}


///다른방식의 검색

public List<CompanyUiItem> SearchTableData(string input)
    {
        if (input.Length == 0)
            return originTable;


        Func<CompanyUiItem,bool> condition_car; //검색 조건
        Func<CompanyUiItem, bool> condition_products; //검색 조건
        Func<CompanyUiItem, bool> condition_companyName; //검색 조건
        Func<CompanyUiItem, bool> condition_companyType; //검색 조건
       
        //Func<CompanyUiItem, object> order; //정렬 기준
        string search = input.ToLower(); //소문자로 변환

        condition_car = item => item.cars.Where(x=> x.ToLower().Contains(search)).Any();
        condition_products = item => item.products.Where(x => x.ToLower().Contains(search)).Any();
        condition_companyName = item => item.companyName.ToLower().Contains(search);
        condition_companyType = item => item.companyType.ToLower().Contains(search);






       
        IEnumerable<CompanyUiItem> result_car;
        IEnumerable<CompanyUiItem> result_products;
        IEnumerable<CompanyUiItem> result_company;
        IEnumerable<CompanyUiItem> result_type;

        result_car = originTable.Where(condition_car);
        result_products = originTable.Where(condition_products);
        result_company = originTable.Where(condition_companyName);
        result_type = originTable.Where(condition_companyType);

        //result = originTable.Where(condition_car).Where(condition_companyName).Where(condition_companyType).Where(condition_products);
        result_car = result_car.Select(x => new CompanyUiItem
        {
            companyName = x.companyName,
            companyType = x.companyType,
            cars = x.cars,
            products = x.products,
            url = x.url,
        });
        result_products = result_products.Select(x => new CompanyUiItem
        {
            companyName = x.companyName,
            companyType = x.companyType,
            cars = x.cars,
            products = x.products,
            url = x.url,
        });
        result_company = result_company.Select(x => new CompanyUiItem
        {
            companyName = x.companyName,
            companyType = x.companyType,
            cars = x.cars,
            products = x.products,
            url = x.url,
        });
        result_type = result_type.Select(x => new CompanyUiItem
        {
            companyName = x.companyName,
            companyType = x.companyType,
            cars = x.cars,
            products = x.products,
            url = x.url,
        });


       

       
        IEnumerable<CompanyUiItem> result  =
            new[] { result_car, result_products, result_company, result_type }.
            Where(x=>x!=null).
            SelectMany(x => x).
            Distinct();

       


        //Debug.Log($"car {result_car.Count()}");
        //Debug.Log($"products {result_products.Count()}");
        //Debug.Log($"result_company {result_company.Count()}");
        //Debug.Log($"result_type {result_type.Count()}");


        //Debug.Log($"result{result.Count()}");

        return result.ToList();
    }

2022년 9월 13일 화요일

unity minimap

 




using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;


//Canvas->RawImage에 넣어서 사용 할 수 있음

public class MiniMapController : MonoBehaviour, IPointerClickHandler
{
    public Camera miniMapCam;
    public GameObject Player;

    public LayerMask mask;
    RaycastHit hit;
    Ray ray;

    public void OnPointerClick(PointerEventData eventData)
    {
        Vector2 curosr = new Vector2(0, 0);

        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RawImage>().rectTransform,
            eventData.pressPosition, eventData.pressEventCamera, out curosr))
        {

            Texture texture = GetComponent<RawImage>().texture;
            Rect rect = GetComponent<RawImage>().rectTransform.rect;

            float coordX = Mathf.Clamp(0, (((curosr.x - rect.x) * texture.width) / rect.width), texture.width);
            float coordY = Mathf.Clamp(0, (((curosr.y - rect.y) * texture.height) / rect.height), texture.height);

            float calX = coordX / texture.width;
            float calY = coordY / texture.height;


            curosr = new Vector2(calX, calY);

           

            CastRayToWorld(curosr);
            //Player.transform.localPosition = GetClickPos(curosr);

            //check();

            //MinimapClick();
        }


    }


    private void CastRayToWorld(Vector2 vec)
    {
        Ray MapRay = miniMapCam.ScreenPointToRay(new Vector2(vec.x * miniMapCam.pixelWidth,
            vec.y * miniMapCam.pixelHeight));

        RaycastHit miniMapHit;

        if (Physics.Raycast(MapRay, out miniMapHit, Mathf.Infinity))
        {
            Debug.Log("miniMapHit: " + miniMapHit.collider.gameObject);

            Player.transform.position = miniMapHit.point;

        }

    }
}



2022년 9월 5일 월요일

xml 삭제

 





using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEngine;

public class XMLManager : MonoBehaviour
{

    private static XMLManager instance = null;


    string xmlFileName = "TestXml";
    string path = "XML";


    void Awake()
    {
        if (null == instance)
        {
            //이 클래스 인스턴스가 탄생했을 때 전역변수 instance에 게임매니저 인스턴스가 담겨있지 않다면, 자신을 넣어준다.
            instance = this;

            //씬 전환이 되더라도 파괴되지 않게 한다.
            //gameObject만으로도 이 스크립트가 컴포넌트로서 붙어있는 Hierarchy상의 게임오브젝트라는 뜻이지만,
            //나는 헷갈림 방지를 위해 this를 붙여주기도 한다.
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            //만약 씬 이동이 되었는데 그 씬에도 Hierarchy에 GameMgr이 존재할 수도 있다.
            //그럴 경우엔 이전 씬에서 사용하던 인스턴스를 계속 사용해주는 경우가 많은 것 같다.
            //그래서 이미 전역변수인 instance에 인스턴스가 존재한다면 자신(새로운 씬의 GameMgr)을 삭제해준다.
            Destroy(this.gameObject);
        }
    }

    public static XMLManager Instance
    {
        get
        {
            if (null == instance)
            {
                return null;
            }
            return instance;
        }
    }


    // Resources/XML/TestItem.XML 파일.
   


    public List<string> LoadComments(string _fileName)
    {
        string pullpath = path + "/" + _fileName;
        TextAsset txtAsset = (TextAsset)Resources.Load(pullpath);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(txtAsset.text);
        List<string> results = new List<string>();
        XmlNodeList all_nodes = xmlDoc.SelectNodes("dataroot/Comment");

        foreach (XmlNode node in all_nodes)
        {
            results.Add(node.SelectSingleNode("type").InnerText + "_" + node.SelectSingleNode("desc").InnerText);
        }

        return results;
    }


    public List<RoadInfo> LoadRoadInfos()
    {
        string pullpath = path + "/" + "RoadList";
        TextAsset txtAsset = (TextAsset)Resources.Load(pullpath);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(txtAsset.text);
        List<RoadInfo> results = new List<RoadInfo>();
        XmlNodeList all_nodes = xmlDoc.SelectNodes("RoadXml/Road");

        foreach (XmlNode node in all_nodes)
        {
            RoadInfo temp = new RoadInfo();
            temp.roadName = node.SelectSingleNode("roadName").InnerText;
            temp.posX = node.SelectSingleNode("posX").InnerText;
            temp.posY = node.SelectSingleNode("posY").InnerText;
           

            results.Add(temp);
        }

        Debug.Log("count" + results.Count);

        return results;
    }


    public void LoadXML(string _fileName)
    {
        string pullpath = path + "/" + _fileName;
        TextAsset txtAsset = (TextAsset)Resources.Load(pullpath);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(txtAsset.text);

        // 하나씩 가져오기 테스트 예제.
        XmlNodeList cost_Table = xmlDoc.GetElementsByTagName("cost");
        foreach (XmlNode cost in cost_Table)
        {
            Debug.Log("[one by one] cost : " + cost.InnerText);
        }

        // 전체 아이템 가져오기 예제.
        XmlNodeList all_nodes = xmlDoc.SelectNodes("dataroot/TestItem");
        foreach (XmlNode node in all_nodes)
        {
            // 수량이 많으면 반복문 사용.
            Debug.Log("[at once] id :" + node.SelectSingleNode("id").InnerText);
            Debug.Log("[at once] name : " + node.SelectSingleNode("name").InnerText);
            Debug.Log("[at once] cost : " + node.SelectSingleNode("cost").InnerText);

            ///한번더 돌리고싶을때
            //foreach (XmlElement element in node)
            //{
            //    Debug.Log(element.InnerText);
            //}


        }

    }

    public void Add_New_Road(RoadInfo _roadInfo)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(GetPath("RoadList.xml"));

        Add_New_Road_Eelement(xmlDoc, _roadInfo);
        xmlDoc.Save(GetPath("RoadList.xml"));
    }

    public void Add_New_Road_Eelement(XmlDocument xmlDoc, RoadInfo _roadInfo)
    {

        XmlNode newNode;
        XmlElement roadElement = xmlDoc.CreateElement("Road"); //엘리멘트를 만든다~

        XmlElement roadName = xmlDoc.CreateElement("roadName");
        XmlElement posX = xmlDoc.CreateElement("posX");
        XmlElement posY = xmlDoc.CreateElement("posY");




        roadName.InnerText = _roadInfo.roadName;
        posX.InnerText = _roadInfo.posX;
        posY.InnerText = _roadInfo.posY;

        roadElement.AppendChild(roadName);
        roadElement.AppendChild(posX);
        roadElement.AppendChild(posY);


        newNode = xmlDoc.SelectSingleNode("RoadXml");
        newNode.AppendChild(roadElement);
    }


    #region 노말함수
    string GetPath(string fileName)
    {
        string path = "";

        if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            //path = Application.dataPath.Substring(0, Application.dataPath.Length - 5);
            //path = path.Substring(0, path.LastIndexOf('/'));
            //Read(Path.Combine(Path.Combine(path, "Documents"), "Dialogue.xml"));
            path = Path.Combine(Path.Combine(Application.persistentDataPath, "Documents"), fileName);
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            path = Path.Combine(Application.persistentDataPath, fileName);
        }
        else
        {
            ///실제 할때는 여기로 해야 모바일에서 된다(원본)
            //path = Path.Combine(Application.persistentDataPath, fileName);
            path = Path.Combine(Application.dataPath + "/Resources/XML/", fileName);

        }

        return path;
    }


    public void DeleteXmlInformation(string xmlFilePath,string deleteElementName)
    {
        try
        {

            Debug.Log("DeleteXmlInformation !!!");

            string pullpath = GetPath(xmlFilePath);

           

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(pullpath);
            XmlNode FirstNode = xmlDoc.DocumentElement;

            foreach (XmlNode Node in FirstNode.SelectNodes(deleteElementName))
            {
                //XmlNode delNode = Node.SelectSingleNode(deleteElementName);
                FirstNode.RemoveChild(Node);
            }

            //XmlNode delNode = FirstNode.SelectSingleNode(deleteElementName);
            //Debug.Log("delNode" + delNode.InnerText);


           

            xmlDoc.Save(GetPath(xmlFilePath));
        }
        catch (Exception ex)
        {
            Debug.Log(ex.ToString());
        }
    }

    #endregion

}

git rejected error(feat. cherry-pick)

 문제 아무 생각 없이 pull을 받지않고 로컬에서 작업! 커밋, 푸시 진행을 해버렷다. push에선 remote와 다르니 당연히 pull을 진행해라고 하지만 로컬에서 작업한 내용을 백업하지 않고 진행하기에는 부담스럽다(로컬작업 유실 가능성) 해결하려...