例如我有一个开关盒,我输入" 1"然后它会提示用户输入特定的口袋,如果我输入" ClientLoginRequest"在客户端消息包内,它应该输出一个字符串,其值为" CLIENTPC_LOGIN_RESPONSE"我怎么做?我的代码只能输出某个节点及其元素,例如它输出程序定义的ConnectionPackets,因此输出为
以下是代码......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Linq;
namespace Packets
{
class Program
{
static void Main(string[] args)
{
string result = "C:\\Users\\Ivan.Apungan\\Documents\\PacketTypes.xml";
using (var stream = new StringReader(result))
{
XDocument xmlfile = XDocument.Load(result);
var query = from c in xmlfile.Descendants("ConnectionPackets") select c;
foreach (var item in query)
{
Console.WriteLine(item.ToString());
}
}
Console.ReadLine();
}
}
}
这是xml文件。
<? xml version="1.0" encoding="utf-8" ?>
<Packets>
<ConnectionPackets>
<PacketType name = "Handshake" > HANDSHAKE </ PacketType >
< PacketType name="HandshakeAcknowledgement">HANDSHAKE_ACKNOWLEDGEMENT</PacketType>
</ConnectionPackets>
<ClientMessagePackets>
<PacketType name = "ClientLoginRequest" > CLIENTPC_LOGIN_REQUEST </ PacketType >
< PacketType name="ClientLoginResponse">CLIENTPC_LOGIN_RESPONSE</PacketType>
</ClientMessagePackets>
</Packets>
例如我有一个开关盒,我输入&#34; 1&#34;然后它会提示用户输入特定的口袋,如果我输入&#34; ClientLoginRequest&#34;在客户端消息包内,它应该输出一个字符串,其值为&#34; CLIENTPC_LOGIN_RESPONSE&#34;我怎么做?我的代码只能输出某个节点及其元素,例如它输出程序定义的ConnectionPackets,因此输出为
<ConnectionPackets>
<PacketType name = "Handshake" > HANDSHAKE </ PacketType >
< PacketType name="HandshakeAcknowledgement">HANDSHAKE_ACKNOWLEDGEMENT</PacketType>
</ConnectionPackets>
答案 0 :(得分:0)
使用System.Xml.Linq扩展来查询xml文档非常简单。如果误解了你的问题,请告诉我。
class Program
{
static void Main(string[] args)
{
string command = string.Empty;
while (command != "exit")
{
XDocument xml = XDocument.Parse(xmlString);
Console.WriteLine("Find packet: ");
command = Console.ReadLine();
var element = xml
.Descendants()
.FirstOrDefault(x => x.Attribute("name")?.Value == command);
if (element == null)
{
Console.WriteLine("Not found");
}
else
{
Console.WriteLine(element.Value);
}
Console.WriteLine(new string('-', 20));
}
}
static string xmlString = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Packets>
<ConnectionPackets>
<PacketType name=""Handshake""> HANDSHAKE </PacketType >
<PacketType name=""HandshakeAcknowledgement"">HANDSHAKE_ACKNOWLEDGEMENT</PacketType>
</ConnectionPackets>
<ClientMessagePackets>
<PacketType name=""ClientLoginRequest"" > CLIENTPC_LOGIN_REQUEST </PacketType >
<PacketType name=""ClientLoginResponse"">CLIENTPC_LOGIN_RESPONSE</PacketType>
</ClientMessagePackets>
</Packets>";
}