2009-05-19 5 views
35

다음 구조로 XML 파일을 동적으로 만들 수 있습니까?XML 노드에 속성 추가

<Login> 
    <id userName="Tushar" passWord="Tushar"> 
     <Name>Tushar</Name> 
     <Age>24</Age> 
    </id> 
</Login> 

나는 id 태그 내부의 특성 (즉는 userName = ""과 암호를 = "") 만들 수 없습니다입니다.

Windows 응용 프로그램에서 C#을 사용하고 있습니다. Login입니다 : 여러분이 필요로하는

일부 중요 네임 스페이스는

using System.Xml; 
using System.IO; 

답변

68

id 정말 루트 노드가 없습니다.

XmlElement.SetAttribute을 사용하여 속성 (태그, btw가 아님)을 지정해야합니다. XmlWriter, DOM 또는 다른 XML API를 사용하든 파일을 만드는 방법을 지정하지 않았습니다.

작동하지 않는 코드의 예를들 수 있다면 많은 도움이 될 것입니다.

using System.Xml.Linq 

     var xmlNode = 
      new XElement("Login", 
         new XElement("id", 
          new XAttribute("userName", "Tushar"), 
          new XAttribute("password", "Tushar"), 
          new XElement("Name", "Tushar"), 
          new XElement("Age", "24") 
         ) 
      ); 
     xmlNode.Save("Tushar.xml"); 

기발한 코딩의 방법 :

using System; 
using System.Xml; 

class Test 
{ 
    static void Main() 
    { 
     XmlDocument doc = new XmlDocument(); 
     XmlElement root = doc.CreateElement("Login"); 
     XmlElement id = doc.CreateElement("id"); 
     id.SetAttribute("userName", "Tushar"); 
     id.SetAttribute("passWord", "Tushar"); 
     XmlElement name = doc.CreateElement("Name"); 
     name.InnerText = "Tushar"; 
     XmlElement age = doc.CreateElement("Age"); 
     age.InnerText = "24"; 

     id.AppendChild(name); 
     id.AppendChild(age); 
     root.AppendChild(id); 
     doc.AppendChild(root); 

     doc.Save("test.xml"); 
    } 
} 
28

XML을 구성하는 최신의 그리고 아마도 가장 큰 방법은 XML에 LINQ를 사용하는 것입니다 : 한편, 여기에 당신이 설명하는 파일을 생성하는 코드입니다 코드가 출력과 닮았 기 때문에 더 쉬워야합니다 (위의 Jon 예제는 그렇지 않습니다). 그러나이 비교적 간단한 예제를 코딩하는 동안 쉼표를 사용하는 사이에 내 길을 잃어 버리는 경향이 있다는 것을 발견했습니다. Visual Studio의 자동 코드 간격은 도움이되지 않습니다.

+4

+1 –

23

어떤 경우에는 유용 ​​할 수있는 XmlNode 개체에 특성을 추가하는 방법이 있습니다.

이 다른 방법은 msdn.microsoft.com에 있습니다.

using System.Xml; 

[...] 

//Assuming you have an XmlNode called node 
XmlNode node; 

[...] 

//Get the document object 
XmlDocument doc = node.OwnerDocument; 

//Create a new attribute 
XmlAttribute attr = doc.CreateAttribute("attributeName"); 
attr.Value = "valueOfTheAttribute"; 

//Add the attribute to the node  
node.Attributes.SetNamedItem(attr); 

[...] 
관련 문제