아래 기능은 파일을 찾고, 지정된 부모 노드로 이동하고 미리 정의 된 요소 이름을 찾는 자식 노드를 통과합니다.XML을 읽는 사례 변환 XML
XML 파일을 읽고 노드 내부 텍스트 값을 정적 필드에 할당하고 특정 노드 만 선택하려는 경우 사용자가 XML 구성 파일을 편집 할 수 있으므로 반드시 순서대로 정렬되지는 않습니다.
현재 노드의 순서대로 하드 코드를 작성해야합니다. 스위치 케이스에 무엇이 잘못된지 알 수 없으므로 중요하지 않다고 생각합니다. 이상하게도 이것을 피하기를 원합니다.
더 나은 대안이 있습니까, 아니면 스위치 케이스에 문제가 있습니까?
내 코드는 의미로 :
public void ReadConfig()
{
string fp = _AppPath + @"\myfolder";
try
{
string confPath = (fp + @"\config.xml");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(configfilepath);
XmlNode xmlLst = xDoc.SelectSingleNode("parentnode/childnode");
foreach (XmlNode node in xmlLst.ChildNodes)
{
switch(node.Name)
{
case "user":
_User = node.InnerText;
break;
case "password":
_Password = node.InnerText;
break;
case "serverip":
_serverIP = node.InnerText;
break;
case "mailport":
_mailPort = int.Parse(node.InnerText);
break;
case "recipient":
_recipient = node.InnerText;
break;
default:
WriteErrorLog("Issue getting server details from XML config file.");
break;
}
}
}
완벽한 솔루션 지원
감사 작업, 아래의 작업 코드입니다.
XmlNode xmlLst = xDoc.SelectSingleNode("parentnode/childnode");
_User = xmlLst.SelectSingleNode("user").InnerText;
_Password = xmlLst.SelectSingleNode("password").InnerText;
....
하거나 XmlDocument
대신, 새로운 XML API를 XDocument
를 사용하여 완전히 다른 경로를 시도 할 수 있습니다 :
public static void ReadFromXMLXDoc()
{
// XDocument xDocu;
string xmlFilePath = (@"somewhere\Config.xml");
XDocument xDocu = XDocument.Load(xmlFilePath);
XElement xmlList = xDocu.Element("configuration").Element("parent").Element("child");
_one = (string)xmlList.Element("option1");
_two = (string)xmlList.Element("option2");
_three = (string)xmlList.Element("option3");
Console.WriteLine(_one + " " + _two + " " + _three);
Console.ReadLine();
}
나를 XDocument로 소개해 주셔서 감사합니다. 훨씬 더 간단합니다. – PurpleSmurph