使用UDP收发XML格式并解析

一、通过UDP将本地xml文件内容发送

1.得到xml所在路径path,注意要以.xml 结尾.就是(文件路径+"/"+文件名+".xml")(不要重复)

 public string GetXmlPath(string xmlLoadPath, string xmlName)
    {
        string xmlname = xmlName;
        if (!xmlname.Contains(".xml"))
        {
            xmlname = xmlName + ".xml";
        }
        string path = xmlLoadPath + "/" + xmlname;
        if (string.IsNullOrEmpty(path) || !File.Exists(path))
        {
            return null;
        }
        return path;
    }

2.根据路径获取到XmlDocument

public XmlDocument GetXmlDocumentByFilePath(string path)
    {
        var xDoc = new XmlDocument();
        try
        {
            xDoc.Load(path);
            
        }
        catch
        {
            throw new Exception(string.Format("请确认该XML文件格式正确,路径为:{0}", path));
        }

        return xDoc;

    }

3.将获取到的XmlDocument转换为字符串

 string path = GetXmlPath(Application.dataPath, "scenelist");
 XmlDocument xmldoc = GetXmlDocumentByFilePath(path);
 string xmlStr=xmldoc.InnerXML;

4.将xmlStr用UDP中的发送方法发送即可。

二、UDP收到XML格式内容后解析

XmlDocument document = new XmlDocument();
document.LoadXml("发送过来的XML信息");
然后利用读取xml文件方法读取document即可.

猜你喜欢

转载自blog.csdn.net/lei_7103/article/details/79607853
今日推荐