Reputation: 356
I have a folder with 40 xml files where I need to remove the <column ..../>
element.
I want to do them all in one go. Here's an example of the files I need modified:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<!-- generated using CMHInc.NHibernate.hbm.cst -->
<class name="CMHInc.Lodge.Business.Core.ProductType, CMHInc.Lodge.Business.Core" table="ProductType" lazy="false" schema="CMHPos">
<id name="Id" type="Guid" unsaved-value="{00000000-0000-0000-0000-000000000000}" >
<column name="Id" sql-type="uniqueidentifier" not-null="true" unique="true" index="PK_ProductType"/>
<generator class="guid.comb" />
</id>
<version name="RowId" column="RowId" generated="always" type="Byte[]"
unsaved-value="null" access="field.camelcase-underscore"/>
<property name="Type" type="String" access="field.camelcase-underscore" >
<column name="Type" length="20" sql-type="varchar" not-null="true"/>
</property>
I would like to remove every instance of
<column name="Type" length="20" sql-type="varchar" not-null="true"/>
Here's my PowerShell code:
Get-ChildItem c:\xml\*.xml | % {
$xml = [xml](Get-Content $_.FullName)
$xml.catalog.book |
where { $_.title -eq "property" } |
foreach { $_.RemoveAttribute("column") }
$xml.Save($_.FullName)
}
I'm having the following errors:
Exception calling "Save" with "1" argument(s): "Access to the path 'C:\xml\ActivityChargeCalculation.hbm.xml' is denied."
I looked up the security settings of the files and folder, but I am logged in as admin and just created those files.
Suggestions?
Upvotes: 0
Views: 3408
Reputation: 200303
Your sample XML is incomplete and does not match your code. Also, you want to remove nodes, not attributes. Try this:
Get-ChildItem C:\xml\*.xml | ForEach-Object {
$xml = [xml](Get-Content $_.FullName)
$xml.SelectNodes("//property/column") | Where-Object {
$_.name -eq "Type" -and
$_.length -eq "20" -and
$_."sql-type" -eq "varchar" -and
$_."not-null" -eq "true"
} | ForEach-Object {
$_.ParentNode.RemoveChildNode($_)
}
$xml.Save($_.FullName)
}
Note that you need to run the script with admin permissions if normal users don't have write permission to the files in C:\xml
.
Upvotes: 1
Reputation: 356
The answer provided by Ansgar was relevant for a specific node of specific name, length (and other properties). My research have enlightened me a bit more onto powershell and the notable would be SelectNodes("//*column"). I ended up doing an itteration using .Net as I am more familiar with it.
Upvotes: 0