your programing

Xml 네임 스페이스로 Linq to Xml 사용

lovepro 2020. 12. 29. 08:05
반응형

Xml 네임 스페이스로 Linq to Xml 사용


이 코드가 있습니다.

/*string theXml =
@"<Response xmlns=""http://myvalue.com""><Result xmlns:a=""http://schemas.datacontract.org/2004/07/My.Namespace"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><a:TheBool>true</a:TheBool><a:TheId>1</a:TheId></Result></Response>";*/

string theXml = @"<Response><Result><TheBool>true</TheBool><TheId>1</TheId></Result></Response>";

XDocument xmlElements = XDocument.Parse(theXml);

var elements = from data in xmlElements.Descendants("Result")
               select new {
                            TheBool = (bool)data.Element("TheBool"),
                            TheId = (int)data.Element("TheId"),
                          };

foreach (var element in elements)
{
    Console.WriteLine(element.TheBool);
    Console.WriteLine(element.TheId);
}

theXml에 대한 첫 번째 값을 사용하면 결과가 null 인 반면 두 번째 값은 좋은 값이 있습니다.

xmlns 값으로 Linq to Xml을 사용하는 방법은 무엇입니까?


같은 XML 방법에 LINQ DescendantsElementXName인수한다. 에서 전환이 stringXName당신을 위해 자동으로 일어나고있는 그. 호출 XNamespace의 문자열 앞에 를 추가하여이 문제를 해결할 수 있습니다 . 직장에 2 개의 서로 다른 네임 스페이스가 있으므로주의하십시오.DescendantsElement


string theXml =
                @"true1";

            //string theXml = @"true1";

    XDocument xmlElements = XDocument.Parse( theXml );
    XNamespace ns = "http://myvalue.com";
    XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";
    var elements = from data in xmlElements.Descendants( ns + "Result" )
          select new
                 {
                     TheBool = (bool) data.Element( nsa + "TheBool" ),
                     TheId = (int) data.Element( nsa + "TheId" ),
                 };

    foreach ( var element in elements )
    {
        Console.WriteLine( element.TheBool );
        Console.WriteLine( element.TheId );
    }

ns in Descendants및 nsa inElements


네임 스페이스가 있는 XNameDescendants ()Element ()에 전달할 수 있습니다 . Descendants ()에 문자열을 전달하면 네임 스페이스가없는 XName으로 암시 적으로 변환됩니다.

네임 스페이스에 XName을 생성하려면 XNamespace를 생성하고이를 local-name 요소 (문자열)에 연결합니다.

XNamespace ns = "http://myvalue.com";
XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";

var elements = from data in xmlElements.Descendants( ns + "Result")
                   select new
                              {
                                  TheBool = (bool)data.Element( nsa + "TheBool"),
                                  TheId = (int)data.Element( nsa + "TheId"),
                              };

문자열에서 암시 적 변환을 통해 네임 스페이스가있는 XName을 만드는 약식 형식도 있습니다.

var elements = from data in xmlElements.Descendants("{http://myvalue.com}Result")
                   select new
                              {
                                  TheBool = (bool)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheBool"),
                                  TheId = (int)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheId"),
                              };

또는 XElement에 대해 쿼리 할 수 ​​있습니다. Name.LocalName .

var elements = from data in xmlElements.Descendants()
                   where data.Name.LocalName == "Result"

XML 문서의 맨 위에 여러 개의 네임 스페이스가 나열되어 있지만 어떤 요소가 어떤 네임 스페이스에서 왔는지는 신경 쓰지 않습니다. 이름으로 요소를 얻고 싶습니다. 이 확장 방법을 작성했습니다.

    /// <summary>
    /// A list of XElement descendent elements with the supplied local name (ignoring any namespace), or null if the element is not found.
    /// </summary>
    public static IEnumerable<XElement> FindDescendants(this XElement likeThis, string elementName) {
        var result = likeThis.Descendants().Where(ele=>ele.Name.LocalName==elementName);
        return result;
    }

I found the following code to work fine for reading attributes with namespaces in VB.NET:

MyXElement.Attribute(MyXElement.GetNamespaceOfPrefix("YOUR_NAMESPACE_HERE") + "YOUR_ATTRIB_NAME")

Hope this helps someone down the road.

ReferenceURL : https://stackoverflow.com/questions/2340411/use-linq-to-xml-with-xml-namespaces

반응형