2013-10-16 14 views
0

과 함께 새 요소 추가 필자가 작성한 Windows 양식 응용 프로그램이 있고 xml 파일을 만들고 데이터를 추가하려고합니다.자식 노드 Xml 및 C#

코드는 다음과 같습니다.

xmlFile = new XDocument(
        new XDeclaration("1.0", "utf-8", "yes"), 
        new XComment("XML File for storing " + RootName)); 
xmlFile.Add(new XElement(RootName)); 

// Loop through the list and create a new element for each item in the list 
foreach (Contact c in contactsList) 
{ 
    try 
    { 
     xmlFile.Add(new XElement("Contact", 
      new XElement("Name", c.Name), 
      new XElement("Email", c.EmailAddress), 
      new XElement("Mobile Number", c.MobileNumber), 
      new XElement("Mobile Carrier", c.sMobileCarrier) 
      ) 
     ); 
    } 
    catch 
    { 
     MessageBox.Show("ERROR WITH NEW ELEMENTS"); 
    } 
} 
xmlFile.Save(FileName); 

프로그램을 실행하면 try 블록이 throw되고 오류가 발생하고 메시지 상자 오류가 발생합니다. 뭔가가, 내가 모든 값과 항목의 지점 개까지 전달되는 확인하기 때문에, 이것은 무엇을 의미하는지 확실하지 않다

The ' ' character, hexadecimal value 0x20, cannot be included in a name. 

: 나는 디버깅 할 때 , 프로그램은 예외과 관련이있다 말한다 .

xmlFile.Add() 문에 매개 변수가 누락 되었습니까?

마지막 질문 하나 XDocument 개체를 만든 후 Root 요소를 삽입하면 파일에 닫는 루트 태그가되고 <Contacts />으로 표시됩니다.

시작 태그를 삽입하려면 어떻게해야합니까? 그리고 마지막에 저장하려면 닫는 태그를 추가합니까?

감사

MarcinJuraszek에 덕분에, 내가 던져지는 것을 제외하고 과거를 얻을 수 있었다 ---------------------

업데이트,하지만 지금 이 오류가 발생합니다 :

This operation would create an incorrectly structured document. 

어떤 아이디어입니까?

답변

2

오류 메시지가 분명합니다. XML 요소 이름에 공백을 사용할 수 없습니다. 당신은 정확하게하려고 노력하고 있습니다 :

 new XElement("Mobile Number", c.MobileNumber), 
     new XElement("Mobile Carrier", c.sMobileCarrier) 

이 줄을 공백이 포함되지 않도록 변경하면 올바르게 작동합니다. 예 :

 new XElement("MobileNumber", c.MobileNumber), 
     new XElement("MobileCarrier", c.sMobileCarrier) 

How do I get the starting tag inserted, and then when I go to save at the end, it appends the closing tag?

는/닫는 태그를 시작 대해 걱정하지 마십시오. XElement.Save 메서드가이를 처리합니다.

업데이트

여기에 두 번째 문제는 여러 루트 요소와 문서를 만들려고하고 있다는 사실이다. 루트 XElement에 새 콘텐츠를 추가하는 대신 XDocument 인스턴스에 직접 추가하려고하기 때문입니다. 다음

시도 :

xmlFile.Root.Add(new XElement("Contact", 
     new XElement("Name", c.Name), 
     new XElement("Email", c.EmailAddress), 
     new XElement("MobileNumber", c.MobileNumber), 
     new XElement("MobileCarrier", c.sMobileCarrier) 
     ) 
+0

대답을 주셔서 감사합니다,하지만 지금은 다른 오류를 얻고있다. 저것에 대한 아이디어가 있습니까? – RXC

+0

답변을 업데이트했습니다. 희망이 당신을 돕는다! – MarcinJuraszek

+0

대단 하시군요, 고마워요! – RXC