2012-02-10 1 views
-2

문서 내에서 특성 "nil = true"로 XML 요소를 정리하려고합니다. 나는이 고고함을 생각해 낸다. 그러나 나는 그것이 어떻게 보이는지에 관해 싫어한다.특성 "nil = true"로 XML 요소를 정리합니다. - linq 버전을 만드시겠습니까?

사람이 너 한테의 LINQ 버전을 알고 계십니까?

/// <summary> 
    /// Cleans the Xml element with the attribut "nil=true". 
    /// </summary> 
    /// <param name="value">The value.</param> 
    public static void CleanNil(this XElement value) 
    { 
     List<XElement> toDelete = new List<XElement>(); 

     foreach (var element in value.DescendantsAndSelf()) 
     { 
      if (element != null) 
      { 
       bool blnDeleteIt = false; 
       foreach (var attribut in element.Attributes()) 
       { 
        if (attribut.Name.LocalName == "nil" && attribut.Value == "true") 
        { 
         blnDeleteIt = true; 
        } 
       } 
       if (blnDeleteIt) 
       { 
        toDelete.Add(element); 
       } 
      } 
     } 

     while (toDelete.Count > 0) 
     { 
      toDelete[0].Remove(); 
      toDelete.RemoveAt(0); 
     } 
    } 
+3

다음을 사용하는 문제를 해결하기 위해 내 방식을 변경하고 내 nullable 형식 에 전무를 만들 피하기 XML 네임 스페이스에 대해서는 언급하지 않았지만 http://www.w3.org/2001/XMLSchema-instance 네임 스페이스 (종종 접두어'xsi'를 사용)는 nil 요소에 대해'true'로 설정할 수있는'nil' 속성을 가지고 있습니다 . 그것이 사용중인 속성 인 경우 응답이 예상대로 작동하지 않는 이유를 설명합니다. 해답은 기본 네임 스페이스에서'nil' 속성을 찾고 XML에서 작동하지 않습니다. –

답변

1

nil 속성의 네임 스페이스 기능 :주의해야 할 유일한 것은 루트 노드를 제거 할 수 있기 때문에 당신이 <Root> 노드에서이 메소드를 호출 할 수 없으며,이 런타임 오류를 얻을 것입니다? 다음과 같이 그 내부에 {} 넣어 :

public static void CleanNil(this XElement value) 
{ 
    value.Descendants().Where(x=> (bool?)x.Attribute("{http://www.w3.org/2001/XMLSchema-instance}nil") == true).Remove(); 
} 
0

이 작동한다 ..

public static void CleanNil(this XElement value) 
{ 
    var todelete = value.DescendantsAndSelf().Where(x => (bool?) x.Attribute("nil") == true); 
    if(todelete.Any()) 
    { 
     todelete.Remove(); 
    } 
} 
+0

미안하지만 작동하지 않습니다! – frankyt79

+0

어떤 오류가 발생 했습니까? – Flowerking

0

연장있어서

public static class Extensions 
{ 
    public static void CleanNil(this XElement value) 
    { 
     value.DescendantsAndSelf().Where(x => x.Attribute("nil") != null && x.Attribute("nil").Value == "true").Remove(); 
    } 
} 

샘플 용도 :

File.WriteAllText("test.xml", @" 
       <Root nil=""false""> 
        <a nil=""true""></a> 
        <b>2</b> 
        <c nil=""false""> 
         <d nil=""true""></d> 
         <e nil=""false"">4</e> 
        </c> 
       </Root>"); 
var root = XElement.Load("test.xml"); 
root.CleanNil(); 
Console.WriteLine(root); 

출력 :

<Root nil="false"> 
    <b>2</b> 
    <c nil="false"> 
    <e nil="false">4</e> 
    </c> 
</Root> 

노드에서 볼 수 있듯이 <a><d>은 예상대로 제거되었습니다.

The parent is missing.

+0

미안하지만 작동하지 않습니다! – frankyt79

+0

@ frankyt79 그것이 작동하지 않는다는 것이 무엇을 의미합니까? 대답에 대한 실례를 추가했습니다. 나는 그것을 테스트하고 작동합니다. – Meysam