I am trying make this XML:
<?xml version="1.0" encoding="UTF-8"?>
<nfeProc>
<NFe>
<infNFe>
<det nItem="1">
<prod>
<vProd>180.00</vProd>
</prod>
<imposto>
<ICMS>
<ICMS00>
<vBC>180.00</vBC>
</ICMS00>
</ICMS>
<PIS>
<PISNT>04</PISNT>
</PIS>
</infNFe>
</NFe>
</nfeProc>
Looks like:
<?xml version="1.0" encoding="UTF-8"?>
<nfeProc>
<NFe>
<infNFe>
<det nItem="1">
<prod>
<vProd>180.00</vProd>
</prod>
<imposto>
<ICMS>
<ICMS00>
<vBC>180.00</vBC>
</ICMS00>
</ICMS>
<PIS>
<PISAliq>0.65</PISAliq>
</PIS>
</infNFe>
</NFe>
</nfeProc>
Couldn't find a easy way to remove the <PISNT>04</PISNT> so I went with this:
($produto.imposto.PIS.ChildNodes | Where-Object {$_.Name -eq "PISNT"}) | ForEach-Object {
[void]$_.ParentNode.RemoveChild($_)
}
I don't like, but works. My problem is to add the node <PISAliq>0.65</PISAliq>, already tried everything that I found and still can't work.
My actual code is:
Get-ChildItem $empresaPath -Filter "*.xml" | ForEach-Object {
[xml]$xml = Get-Content $_.FullName
$produtos = $xml.nfeProc.NFe.infNFe.det
foreach ($produto in $produtos) {
$cfop = $produto.prod.CFOP
if ($cfop -eq "5102") {
$prodVprod = $produto.prod.vProd
$produto.imposto.ICMS.ICMS00.vBC = $prodVprod
if ($produto.imposto.PIS.PISNT) {
($produto.imposto.PIS.ChildNodes | Where-Object {$_.Name -eq "PISNT"}) | ForEach-Object {
[void]$_.ParentNode.RemoveChild($_)
}
$xmlElt = $produto.imposto.PIS.CreateElement("PISAliq")
$xmlText = $produto.imposto.PIS.CreateTextNode("0.65")
$xmlElt.AppendChild($xmlText)
$xmlElt = $xml.CreateElement("PISAliq")
$xmlText = $xml.CreateTextNode("0.65")
$xmlElt.AppendChild($xmlText)
}
$xml.Save($_.FullName)
}
else {
Write-Host "$($_.BaseName) CFOP $($cfop) inválido" -ForegroundColor Red
}
}
}
I get this error using this code:
+ CategoryInfo : InvalidOperation: (CreateElement:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Why is so hard add one tag on PowerShell? I appreciate any help, thanks in advance for your time.
.CreateElement()and.CreateTextNode()on an element node ($produto.imposto.PIS); these methods only exist at the document level ($xml), as also present in your code. The other problem is that you're not adding the text child node to the newly created element - Sage's answer shows how to fix that (just assign to.InnerText).