IronPython操作xml原创
金蝶云社区-htv
htv
15人赞赏了该文章 150次浏览 未经作者许可,禁止转载编辑于2024年07月22日 08:39:30

机翻,源自:比邻星

import clr
clr.AddReference('System.Xml')
from System.Xml import XmlDocument, XmlNode, XmlNodeList, XmlElement

class XmlHelper:
    @staticmethod
    def AppendChild(filePath, xPath, xmlNode):
        try:
            doc = XmlDocument()
            doc.Load(filePath)
            xn = doc.SelectSingleNode(xPath)
            n = doc.ImportNode(xmlNode, True)
            xn.AppendChild(n)
            doc.Save(filePath)
            return True
        except:
            return False

    @staticmethod
    def AppendChildFromAnotherXml(filePath, xPath, toFilePath, toXPath):
        try:
            doc = XmlDocument()
            doc.Load(toFilePath)
            xn = doc.SelectSingleNode(toXPath)

            xnList = XmlHelper.ReadNodes(filePath, xPath)
            if xnList is not None:
                for xe in xnList:
                    n = doc.ImportNode(xe, True)
                    xn.AppendChild(n)
                doc.Save(toFilePath)
            return True
        except:
            return False

    @staticmethod
    def UpdateNodeInnerText(filePath, xPath, value):
        try:
            doc = XmlDocument()
            doc.Load(filePath)
            xn = doc.SelectSingleNode(xPath)
            xe = xmlNode.Cast(XmlElement)
            xe.InnerText = value
            doc.Save(filePath)
            return True
        except:
            return False

    @staticmethod
    def LoadXmlDoc(filePath):
        try:
            doc = XmlDocument()
            doc.Load(filePath)
            return doc
        except:
            return None

    @staticmethod
    def ReadNodes(filePath, xPath):
        try:
            doc = XmlDocument()
            doc.Load(filePath)
            xn = doc.SelectSingleNode(xPath)
            xnList = xn.ChildNodes  # Get the node's child nodes
            return xnList
        except:
            return None

# 使用示例
# xmlFilePath = 'path_to_your_xml_file.xml'
# appended = XmlHelper.AppendChild(xmlFilePath, "Your/Xpath/Here", yourXmlNode)
# if appended:
#     print("Node appended successfully.")
# else:
#     print("Failed to append node.")


图标赞 15
15人点赞
还没有人点赞,快来当第一个点赞的人吧!
图标打赏
0人打赏
还没有人打赏,快来当第一个打赏的人吧!