Search XML file *based* on search criteria and remove nodes - ASP or PHP [duplicate]
Possible Duplicate:
A simple program to CRUD node and node values of xml file
I am not looking for an exact attribute or and exact node text. Example
<Items>
<book>
<title> Beginning Java </title>
</book>
<book>
<title> Beginning ASP </title>
</book>
<book>
<title> Beginning Java </title>
</book>
<book>
<title> Advance Java </title>
</book>
<book>
<title> Advance ASP </title>
</book>
</items>
What I want to be able too is find all books that has "Beginning" in the title or "Advance" in the title. Sort of wild type search. What do I need, XPATH? Either ASP.NET or PHP code will help.
I am doing this to write a utility to remove broken links in iTunes music library on MAC.
Thank you
Edit: Help needed with the actual XML I am searching based on the in front of "Location" key. Never came across such an XML which has and .
Thanks again
<key>5175</key>
<dict>
<key>Track ID</key><integer>5175</integer>
<key>Name</key><string>02 - Track 02</string>
<key>Artist</key><string>Abba</string>
<key>Album</key><string>Abba Gold</string>
<key>Genre</key><string>English</string>
<key>Kind</key><string>MPEG audio file</string>
<key>Size</key><integer>5816448</integer>
<key>Total Time</key><integer>242285</integer>
<key>Track Number</key><integer>2</integer>
<key>Date Modified</key><date>2003-09-28T14:37:38Z</date>
<key>Date Added</key><date>2011-06-19T20:30:08Z</date>
<key>Bit Rate</key><integer>开发者_Go百科;192</integer>
<key>Sample Rate</key><integer>44100</integer>
<key>Persistent ID</key><string>9030665BDB2B4A20</string>
<key>Track Type</key><string>File</string>
<key>Location</key><string>file://localhost/Users/macbookpro/Music/iTunes/iTunes%20Media/Music/Abba/Abba%20Gold/02%2002%20-%20Track%2002.mp3</string>
<key>File Folder Count</key><integer>5</integer>
<key>Library Folder Count</key><integer>1</integer>
</dict>
In terms of XPath (1.0) which ASP.NET and PHP support with the normal installations you can use /Items/book[contains(title, 'Beginning') or contains(title, 'Advance')]
. Note that XML node names and therefore XPath expressions are case-sensitive, your sample is not well-formed XML as it has a start tag <Items>
but an end tag </items>
.
As for code to remove nodes with ASP.NET, try along the following lines:
XmlDocument doc = new XmlDocument();
doc.Load("input.xml");
XmlNodeList booksToRemove = doc.SelectNodes("/Items/book[contains(title, 'Beginning') or contains(title, 'Advance')]");
for (int i = booksToRemove.Length - 1; i >= 0; i--) {
booksToRemove[i].ParentNode.RemoveChild(booksToRemove[i]);
}
doc.Save("output.xml");
//book[contains(title, 'Beginning') or contains(title, 'Advance')]
This should do it
精彩评论