문제

나는 여전히 XML과 함께 놀고 있습니다. 이제 다음과 같은 파일이 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<Attributes>
 <AttributeSet id="10110">
  <Attribute id="1">some text here</Attribute>
  <Attribute id="2">some text here</Attribute>
  <!-- 298 more Attribute nodes follow -->
  <!-- note that the value for the id attribute is numbered consecutively -->
 </AttributeSet>
</Attributes>

총 300 개의 속성 노드가 있으며 대부분은 필요하지 않습니다. 내가하고 싶은 것은 ID 속성에 지정된 값이없는 모든 속성 노드를 제거하는 것입니다. 약 10 값의 문자열 배열을 설정했습니다. 이 값은 XML에 보관하고 싶은 속성을 나타냅니다. 나머지는 제거하고 싶습니다.

아래 코드와 함께하려는 것은 사용하고 싶지 않은 모든 속성 노드를 제거하여 XML을 수정하는 것입니다.

Dim ss() As String = New String() {"39", "41", "38", "111", "148", "222", "256", "270", "283", "284"} 'keep the Attributes whose id value is one of these numbers
Dim rv As New List(Of String)'will hold Attribute ids to remove
Dim bool As Boolean = False
For Each x As XElement In doc...<eb:Attribute>
 For Each s As String In ss
  If x.@id = s Then
   bool = True
   Exit For
  End If
 Next
 If bool = True Then
  'do nothing
 Else 'no attribute matched any of the attribute ids listed mark xelement for removal
  rv.Add(x.@id)
 End If
Next
'now remove the xelement
For Each tr As String In rv
 Dim h As String = tr
 doc...<eb:Attribute>.Where(Function(g) g.@id = h).Remove()
Next
'save the xml
doc.Save("C:\myXMLFile.xml")

어떤 이유로 내 코드가 작동하지 않습니다. 바람직하지 않은 속성 노드는 제거되지 않습니다.

뭐가 문제 야? ID 속성 값이 내 문자열 배열의 숫자와 일치하지 않는 속성 노드를 어떻게 제거 할 수 있습니까?

미리 감사드립니다.

추신 - 나는 내 문제를 설명하는 데 분명해지기를 바랍니다.

도움이 되었습니까?

해결책

괜찮아요. 나는 그것을 알아. 여기서 내가 한 일 :

For Each x As XElement In doc...<eb:Attribute>
 **bool = False 'I simply added this line of code and everything worked perfectly**
 For Each s As String In ss
  If x.@id = s Then
   bool = True
   Exit For
  End If
 Next
 If bool = True Then
  'do nothing
 Else 'no attribute matched any of the attribute ids listed so remove the xelement
  rv.Add(x.@id)
 End If
Next

다른 팁

원치 않는 노드를 모두 제거하십시오.

XDocument xDoc = XDocument.Load(xmlFilename);

List<string> keepList = new List<string> { "1", "2", "3" };

var unwanted = from element in xDoc.Elements("Attributes").Elements("AttributeSet").Elements("Attribute")
               where !keepList.Contains((string)element.Attribute("id"))
               select element;

unwanted.Remove();

xDoc.Save(xmlFilename);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top