如果父节点的任何子节点没有值,我想删除它。
我尝试了几种方法,但没有任何效果。如果子节点“ E_Code_List_Qualifier”或“ E_Industry_Code为空”,请删除“ S_Industry_Code”父级及其所有子节点。我想要一个通用的情况,以便该代码也可以在其他空的父或子节点中使用。请帮忙! >
namespace TEST
{
class Remove_Empty_Tags
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Users\TestDLMS\out\I_636806391809983753.xml");
new RemoveNulls().RemoveEmptyNodes(doc);
doc.Save(@"C:\users\Desktop\AllNullsRemoved.xml");
}
}
}
class RemoveNulls
{
public void RemoveEmptyNodes(XmlDocument doc)
{
XmlNodeList nodes = doc.SelectNodes("//node()");
foreach (XmlNode node in nodes)
if ((node.Attributes != null && node.Attributes.Count == 0) && (node.ChildNodes != null && node.ChildNodes.Count == 0))
{
// node.ParentNode.RemoveChild(node); //removes only nodes that are blank
node.ParentNode.RemoveAll(); //removes child nodes leaves empty parent
// node.ParentNode.ParentNode.RemoveAll(); //removes everything
}
}
}
// Content of XML file
<File>
<T_Requisition_511R Standard="X12">
<S_Transaction_Set_Header>
<E_Transaction_Set_Code>511</E_Transaction_Set_Code>
<E_Transaction_Set_Number>0001</E_Transaction_Set_Number>
</S_Transaction_Set_Header>
<S_Beginning_Segment_for_Material_Management>
<E_Transaction_Set_Purpose_Code>00</E_Transaction_Set_Purpose_Code>
<E_Transaction_Type_Code>A0</E_Transaction_Type_Code>
<E_Date>20181217</E_Date>
<E_Time>152620</E_Time>
</S_Beginning_Segment_for_Material_Management>
<L_Assigned_Number>
<L_Code_Source_Information>
<S_Industry_Code>
<E_Code_List_Qualifier_Code>A9</E_Code_List_Qualifier_Code>
<E_Industry_Code> </E_Industry_Code>
</S_Industry_Code>
<S_Industry_Code>
<E_Code_List_Qualifier_Code>79</E_Code_List_Qualifier_Code>
<E_Industry_Code>03</E_Industry_Code>
</S_Industry_Code>
<S_Industry_Code>
<E_Code_List_Qualifier_Code>80</E_Code_List_Qualifier_Code>
<E_Industry_Code> </E_Industry_Code>
</S_Industry_Code>
</L_Code_Source_Information>
</L_Assigned_Number>
</T_Requisition_511R>
</File>
答案 0 :(得分:0)
您不检查属性是否为空的情况。
使用XDocument和XmlDocument可以简化IMO。这是一个示例:
void Main()
{
var doc = XDocument.Load(@"D:\file.xml");
doc = RemoveNulls.RemoveEmptyNodes(doc);
doc.Dump();
}
// Define other methods and classes here
class RemoveNulls
{
public static XDocument RemoveEmptyNodes(XDocument doc)
{
foreach (XElement element in doc.Descendants().ToList()){
if(!element.HasAttributes && String.IsNullOrWhiteSpace(element.Value) && !element.HasElements)
element.Remove();
}
return doc;
}
}
答案 1 :(得分:0)
results = [k for k, v in sorted(d.items(), key=lambda i: i[1], reverse=True)]
# ['kik', 'jjd', 'ddf']