1

属性に基づいて呼び出されたCreditCardノードを削除しようとしていますが、意図したとおりに機能していません。XDocumentdocname

docXDocumentであり、次のようになります。

XDocument doc = new XDocument(
                new XComment("XML test file"),
                new XElement("CreditCards",
                    new XElement("CreditCard",
                        new XAttribute("Name", "TestCard1"),
                        new XAttribute("phoneNumber", 121212142121)),
                    new XElement("CreditCard",
                        new XAttribute("Name", "TestCard2"),
                        new XAttribute("phoneNumber", 6541465561)),
                    new XElement("CreditCard",
                        new XAttribute("Name", "TestCard3"),
                        new XAttribute("phoneNumber", 445588))
                )
            );

これは私が実行しようとしているクエリですが、ノードは削除されません。name何を削除するかを指示するための参照としてこの関数に渡す文字列です

var q = from node in doc.Descendants("CreditCards")
                        let attr = node.Attribute("name")
                        where attr != null && attr.Value == name
                        select node;
q.ToList().ForEach(x => x.Remove());

これでエラーは発生しませんが、何も削除されません。

4

2 に答える 2

2

クエリに属性の小文字の名前がありますname。しかし、あなたのxmlでは属性の名前はですName。Xmlでは大文字と小文字が区別されます。また、属性Nameは要素の子であり、CreditCard要素の子ではありませんCreditCards

doc.Descendants("CreditCards")
   .Elements()
   .Where(c => (string)c.Attribute("Name") == name) 
   .Remove();
于 2013-03-25T10:48:32.590 に答える
1

あなたのコードは、「 CreditCard」ではなく、名前の付いた「 CreditCards 」を探しています。また、サンプルドキュメントのどこにも属性を使用していません。

次のことを試してください。

doc.Descendants("CreditCard")
   .Where(x => (string)x.Element("Name") == name)
   .Remove();
于 2013-03-25T10:23:21.900 に答える