sourcecode

XML 문자열을 XmlElement로 변환해야 합니다.

copyscript 2023. 10. 11. 20:54
반응형

XML 문자열을 XmlElement로 변환해야 합니다.

유효한 XML을 포함하는 문자열을 가장 간단한 방법으로 변환하는 방법을 찾고 있습니다.XmlElementC#의 개체.

이걸 어떻게 이렇게 만들 수가 있죠?XmlElement?

<item><name>wrench</name></item>

사용 방법:

private static XmlElement GetElement(string xml)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    return doc.DocumentElement;
}

조심하세요!!이 요소를 다른 문서에 먼저 추가해야 할 경우 다음을 사용하여 가져오기가 필요합니다.ImportNode.

자식 노드가 있는 XmlDocument가 이미 있고 문자열에서 자식 요소를 추가해야 한다고 가정합니다.

XmlDocument xmlDoc = new XmlDocument();
// Add some child nodes manipulation in earlier
// ..

// Add more child nodes to existing XmlDocument from xml string
string strXml = 
  @"<item><name>wrench</name></item>
    <item><name>screwdriver</name></item>";
XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
xmlDocFragment.InnerXml = strXml;
xmlDoc.SelectSingleNode("root").AppendChild(xmlDocFragment);

결과:

<root>
  <item><name>this is earlier manipulation</name>
  <item><name>wrench</name></item>
  <item><name>screwdriver</name>
</root>

XmlDocument를 사용합니다.LoadXml:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
XmlElement root = doc.DocumentElement;

(또는 XElement를 말하는 경우에는 XDocument를 사용합니다.구문 분석:)

XDocument doc = XDocument.Parse("<item><name>wrench</name></item>");
XElement root = doc.Root;

XmlDocument를 사용할 수 있습니다.이렇게 하려면 Xml()을(를) 로드합니다.

간단한 예는 다음과 같습니다.

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.LoadXml("YOUR XML STRING"); 

이 토막글로 해봤는데 해결책이 있어요

// Sample string in the XML format
String s = "<Result> No Records found !<Result/>";
// Create the instance of XmlDocument
XmlDocument doc = new XmlDocument();
// Loads the XML from the string
doc.LoadXml(s);
// Returns the XMLElement of the loaded XML String
XmlElement xe = doc.DocumentElement;
// Print the xe
Console.out.println("Result :" + xe);

동일한 방법을 구현할 수 있는 더 나은/효율적인 방법이 있다면 알려주시기 바랍니다.

Thanks & Cheers

언급URL : https://stackoverflow.com/questions/3703127/i-need-to-convert-an-xml-string-into-an-xmlelement

반응형